iOS 8是否打破了NSURLCache?

问题描述:

长话短说,我刚刚更新到Xcode 6来检查我的应用程序在iOS 8上是如何工作的。我注意到它不使用缓存,即使它应该。我正在使用AFNetworking设置cachePolicy,如下所示:

Long story short, I just updated to Xcode 6 to check how my app works on iOS 8. I noticed that it doesn't use the cache even though it should. I'm using AFNetworking setting the cachePolicy like this:

sessionManager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

我还有一个iOS 7设备,我在其中测试了相同的代码,它按预期工作。

I still have an iOS 7 device in which I tested the same code and it works there as expected.

有没有人有这方面的解决方案,还是我们需要等待Apple修复它?

Does anyone have a solution for this, or do we need to wait for Apple to fix it?

我几乎可以肯定iOS 8.0已经破解了 NSURLSession 缓存HTTP响应数据的能力。我已经向Apple公开了关于这个问题的雷达。

I'm almost certain that iOS 8.0 has broken NSURLSession's ability to cache HTTP response data. I've opened a radar with Apple about this issue.

这里是我编写的一些示例代码来证明这一点:

Here's some sample code I wrote to prove this:

NSURLSession *session = [NSURLSession sharedSession];
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                     diskCapacity:32 * 1024 * 1024
                                                         diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURL *URL = [NSURL URLWithString:@"http://i.imgur.com/b5pyONe.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                         cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                     timeoutInterval:5];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"Error occurred");
    } else {
        NSLog(@"Fetched resource!");
    }
    dispatch_semaphore_signal(semaphore);
}];
[task resume];

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

request = [NSURLRequest requestWithURL:URL
                           cachePolicy:NSURLRequestReturnCacheDataDontLoad
                       timeoutInterval:5];
task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"Something bad happened: %@", error);
    } else {
        NSLog(@"Fetched resource!");
    }
}];
[task resume];

甚至创建自己的 NSURLSession - 您自己创建的 NSURLSessionConfiguration 具有 NSURLCache - 将无法解决此问题。现在,如果您需要严重缓存响应,则必须使用 NSURLConnection

Even creating your own NSURLSession -- with an NSURLSessionConfiguration that has an NSURLCache that you create yourself -- won't fix this issue. For now, if you need cached responses badly, you have to use NSURLConnection.