AFNetworking下载文件的缓存

时间:2017-04-06 07:50:14

标签: ios objective-c afnetworking-3

我使用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);
}];

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

1 个答案:

答案 0 :(得分:1)

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

将缓存设置为伙伴,然后使用您自己的代码进行下载,它将起作用。

- (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];
}
相关问题