gpt4 book ai didi

ios - AFNetworking 下载文件的缓存

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:25 26 4
gpt4 key购买 nike

我正在使用 AFNetWorking 下载文件。它运行良好。我将文件存储在“/Documents”中。但是当我再次调用此请求时,该应用程序再次下载。是否有任何解决方案可以像 NSURLCache 一样缓存这些文件?当我再次请求时,AF 在文件夹中找到它,然后无需再次下载即可阅读。

这是我的代码。

AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];

manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSString * urlString = @"http://wiki.chinaxue.com/images/e/ee/super.docx";
NSString * string = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSURLRequest * requesturl = [NSURLRequest requestWithURL:[NSURL URLWithString:string]];

NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:requesturl progress:^ (NSProgress * _Nonnull downloadProgress) {
//
NSLog(@"%lld---%lld",downloadProgress.totalUnitCount, downloadProgress.completedUnitCount);
} destination:^NSURL *_Nonnull(NSURL *_Nonnull targetPath, NSURLResponse * _Nonnull response) {

NSString * DocumentPath = [KYCachedManager Share].documentPath; // filePath where download files stored

NSString * documentName = [NSString stringWithFormat:@"%@",response.suggestedFilename];
NSString *path = [DocumentPath stringByAppendingPathComponent:documentName];

MBLog(@"%@",path);

return [NSURL fileURLWithPath:path];

} completionHandler:^(NSURLResponse *_Nonnull response, NSURL * _Nullable filePath,NSError * _Nullable error) {
MBLog(@"%@",filePath);
complete(filePath);
}];

我试图从 downloadTask 获取“response.suggestedFilename”但失败了。另一个问题:如何在没有请求的情况下获得 response.suggestedFilename ?然后我可以使用 fileManager 自己找到它。如果找到阅读其他请求。

最佳答案

AFNetworking 利用了 NSURLCache 已经提供的缓存功能,但您需要进行设置。

将缓存设置为 fellow,然后使用您自己的代码进行下载就可以了。

- (void)setupCache 
{
NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024*4 // 1MB mem
cachediskCapacity:1024*1024*5 // 5MB disk cache
diskPath:nil];
[NSURLCache setSharedURLCache:urlCache];
}
//for lower iphone device like iphone 5
- (void)setupCache
{
SDURLCache *urlCache = [[SDURLCache alloc] initWithMemoryCapacity:1024*1024 // 1MB mem cache
diskCapacity:1024*1024*5 // 5MB disk cache
diskPath:[SDURLCache defaultCachePath]];
[NSURLCache setSharedURLCache:urlCache];
}

关于ios - AFNetworking 下载文件的缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43248949/

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