我已经配置了会话:
- (void)createSession {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
_session = [NSURLSession sessionWithConfiguration:sessionConfig];
}
然后,我尝试向服务器发出请求(从 Twitter 的 API 获取图像):
NSURL *url = tweet.mediaUrl;
NSURLSessionDownloadTask *getImageTask =
[_session downloadTaskWithURL:url
completionHandler:^(NSURL *location,
NSURLResponse *response,
NSError *error) {
UIImage *downloadedImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:location] ];
dispatch_async(dispatch_get_main_queue(), ^{
//setting image to a view
});
}];
[getImageTask resume];
图像正在加载并正确设置,但是当我关闭机器上的 Internet 连接时(没有终止应用程序,它仍然运行......)我得到了空的 UIImageViews - 所以会话尝试从服务器下载图像,但没有使用任何缓存。
是什么导致了这个问题?
我尝试使用共享会话,或者使用预定义的磁盘和内存空间配置共享缓存,但没有任何帮助。
iOS模拟器,iOS 8+