只需使用“sendAsynchronousRequest”方法。这是我的解决方案,它就像一个魅力。
[NSURLConnection sendAsynchronousRequest:newRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data,NSError *error){
NSLog(@"--- caching ---");
if (error) {
NSLog(@"%@", error);
NSLog(@"not cached: %@", absoluteString);
}
NSString *filename = [self sha1:absoluteString];
NSString *path = [cacheDirectory stringByAppendingPathComponent:filename];
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager createFileAtPath:path contents:data attributes:nil];
[fileManager release];
NSURLResponse *newResponse = [[NSURLResponse alloc] initWithURL:response.URL MIMEType:response.MIMEType expectedContentLength:data.length textEncodingName:nil];
NSDictionary *responseInfo = [NSDictionary dictionaryWithObjectsAndKeys:filename, @"filename", newResponse.MIMEType, @"MIMEType", nil];
[responsesInfo setObject:responseInfo forKey:absoluteString];
cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:newResponse data:data];
[newResponse release];
[cachedResponses setObject:cachedResponse forKey:absoluteString];
[cachedResponse release];
}];
因为它只适用于iOS5.0及更高版本。您可能需要先检查 ios 版本。