我是AFNetworking的新手,在iOS開發方面經驗不足。緩存使用AFNetworking的大圖
我用AFNetworking從互聯網上下載圖像,這裏是代碼:
- (void)dowloadPoject {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
BOOL __block responseFromCache = YES; // yes by default
void (^requestSuccessBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseFromCache) {
// response was returned from cache
NSLog(@"RESPONSE FROM CACHE: %@", responseObject);
}
else {
// response was returned from the server, not from cache
NSLog(@"RESPONSE From Server: %@", responseObject);
}
UIImage *downloadedImage = [[UIImage alloc] init];
downloadedImage = responseObject;
// Add & Reload Data
[self.projectImage addObject:downloadedImage];
[self.projectname addObject:@"ABC"];
[self reloadComingSoonProject];
[self reloadNewReleaseProject];
};
void (^requestFailureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"ERROR: %@", error);
};
AFHTTPRequestOperation *operation = [manager GET:@"http://i359.photobucket.com/albums/oo34/SenaSLA/walls/Forward-Arrow-Button.png"
parameters:nil
success:requestSuccessBlock
failure:requestFailureBlock];
operation.responseSerializer = [AFImageResponseSerializer serializer];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"bytesRead: %u, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", bytesRead, totalBytesRead, totalBytesExpectedToRead);
[self.viewNavBar.progressbar setProgress:(totalBytesRead/totalBytesExpectedToRead) animated:YES];
}];
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
// this will be called whenever server returns status code 200, not 304
responseFromCache = NO;
return cachedResponse;
}];
}
我一直在尋找互聯網上,我仍然沒有得到正確的解決方案。我已經嘗試了rckoenes這個解決方案,但是這對我沒有任何作用。
我已經成功緩存像4kb的圖像,但是當我嘗試像103kb的圖像它不緩存。謝謝。
不相關,但是你的代碼說'UIImage * downloadedImage = [[UIImage alloc] init]; downloadedImage = responseObject;'可以簡化爲'UIImage * downloadedImage = responseObject;'。 – Rob 2015-04-02 05:19:16
好的,謝謝。 – 2015-04-02 06:29:27