NSURLRequest缓存无法正常工作 [英] NSURLRequest with caching not working
问题描述
我正在尝试缓存我的nsurlrequest数据。在此之前,我成功地从服务器下载数据,自从我尝试实现此缓存以来,它一直在使我的应用程序崩溃。我希望有人可以查看我到目前为止的代码,并帮助我实现它...我认为我已经完成了大约95%的工作。
I am trying to cache my nsurlrequest data. Prior to this i was successfully downloading data from the server, ever since I tried to implement this cache its been making my application fall over. Im hoping someone can look at the code i have so far and help me to get it workig.. I think I have roughly 95% of it done.
- (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];
}
}];
}
推荐答案
请点击此链接,了解使用NSURLConnection上的类别方法执行此操作的简单方法。它适用于异步请求,但可以很容易地适应同步请求。
Follow this link for an dead simple way of doing this using a category method on NSURLConnection. It's for asynchronous requests but can be adapted easily for synchronous ones.
此外,我强烈建议您为NSOperationQueue使用私有属性或实例变量,以便所有请求都使用相同的操作队列。
Also I strongly advise that you use a private property or instance variable for your NSOperationQueue so that all your requests use the same operation queue.
这篇关于NSURLRequest缓存无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!