使用 AFNetworking 缓存较大的图像

Caching Larger Image Using AFNetworking

我是 AFNetworking 的新手,在 iOS 开发方面的经验较少。

我使用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 这样的图像时它没有缓存。谢谢。

您可以尝试增加缓存大小。上次我对此进行测试时,如果接收到的数据超过总缓存大小的 5%,网络代码将不会缓存(尽管令人恼火的是,我还没有看到 Apple 清楚地阐明缓存期间应用的规则)。

无论如何,如果您查看示例 AFNetworking 项目中的应用委托,它会显示如何指定缓存大小的示例:

NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:cache];

看起来默认的内存缓存只有0.5mb,磁盘缓存有10mb。通过将该 RAM 缓存增加到 4mb,如上所示,或更大,您应该能够缓存您的 103kb 图像(假设所有其他条件,例如响应的 header 字段等,允许它).