我无法在iOS8上实现NSURLCache的简单实现。我的理解是,一旦创建了共享缓存,它就会使用适当的缓存策略自动缓存数据请求。除非您要自定义行为,否则无需配置。这是对的吗?
我在下面提供了我的代码的简化版本。缓存是在AppDelegate中创建的,需要数据的TableViewController使用APICaller对象进行调用。请求正在使用NSURLRequestReturnCacheDataElseLoad
,因为此信息不需要经常更新。
如果我在这里离开了标记。下一步是什么?收到的数据是95KB。
的AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
return YES;
}
TableViewController:
- (void)viewDidLoad {
APICaller *apiCaller = [APICaller alloc] init];
[apiCaller makeAPICallWithCompletionHandler:^(NSArray *result, NSError *error){
if (error) {
// Handle error
} else {
self.property = [result mutableCopy];
[self.tableView reloadData];
}
}
}
APICaller:
- (void)makeAPICallWithCompletionHandler:(void(^)(NSArray *result, NSError *error))completionHandler
{
NSString *urlString = [NSString stringWithFormat@"https://api.apiwebsite.com/json/query?key=@", API_KEY];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
NSURLSessionConfiguration *config = [NSURLSession defaultSessionConfiguration];
self.urlSession = [URLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionDataTask *dataTask = [self.URLSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"There was an error");
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(nil, error);
});
} else {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedResult = [dict[@"result"] sortedArrayUsingDescriptors:sortDescriptors];
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(sortedResponse, error);
});
}
}];
[dataTask resume];
}