gpt4 book ai didi

ios - 使用 AFNetworking 缓存较大的图像

转载 作者:行者123 更新时间:2023-11-29 02:09:50 24 4
gpt4 key购买 nike

我是 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 项目中的应用委托(delegate),它会显示如何指定缓存大小的示例:

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

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

关于ios - 使用 AFNetworking 缓存较大的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com