我想缓存我的nsurlrequest数据。在此之前,我成功地从服务器下载数据,自从我试图实现这个缓存以来,它一直让我的应用程序崩溃。我希望有人可以看看我到目前为止的代码,并帮助我搞定它。我认为我已经完成了大约95%的工作。NSURLRequest缓存不起作用
- (IBAction)setRequestString:(NSString *)string
{
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"http://127.0.0.1:29/"]; // imac development
//PHP file name is being set from the parent view
[databaseURL appendString:string];
//call ASIHTTP delegates (Used to connect to database)
NSURL *url = [NSURL URLWithString:databaseURL];
//SynchronousRequest to grab the data, also setting up the cachePolicy
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0]; //if request dose not finish happen within 60 second timeout.
//This nsdata will be used to put the cache into
NSData *cacheData = [[NSData alloc] init];
//Create my own NSCachedURLResponse and add it to the cache
NSURLResponse *responseToCache = [[NSURLResponse alloc] initWithURL:url MIMEType:@"text/xml" expectedContentLength:[cacheData length] textEncodingName:nil];
//Set up the cache
NSCachedURLResponse *cacheResponse = [[NSCachedURLResponse alloc] initWithResponse:responseToCache data:cacheData];
[[NSURLCache sharedURLCache] storeCachedResponse:cacheResponse forRequest:request];
//check if its really there
NSLog(@"cache = %@", [[NSURLCache sharedURLCache] cachedResponseForRequest:request]);
//If no cache do this stuff, connect to the db and perform these actions. I think this is what i am supposed to be doing.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
[self receivedData:data];
}else if ([data length] == 0 && error == nil){
[self emptyReply];
}else if (error != nil && error.code == NSURLErrorTimedOut){
[self timedOut];
}else if (error != nil){
[self downloadError:error];
}
}];
}
只包含链接的答案是[认为不好的做法](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers)。请总结这里的内容(不要复制/粘贴),这样答案就可以独立运作。如果你不这样做,那么你的答案就会被删除,特别是如果链接死亡的话。 – 2012-05-31 09:15:46
猜猜看,链接刚刚死亡(而不是来自塞尔达的链接)。 – 2012-10-11 13:35:42
链接已经死了 – TrekOnTV2017 2013-05-29 17:29:17