AFNetworking缓存下载文件

问题描述:

我正在使用AFNetWorking.Its正常下载文件。我将文件存储在“/ Documents”中,但是当我再次调用此请求时,应用程序再次下载。有没有解决方案可以像NSURLCache那样缓存这些文件?当我再次请求并且AF在文件夹中找到它时,请再次阅读,而无需再次下载。AFNetworking缓存下载文件

这是我的代码。

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已提供的缓存功能,但需要进行设置。

设置缓存为伙伴,然后使用您自己的代码下载它会工作。

- (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]; 
} 
+1

我按步骤运行应用程序。我首先请求并退出文件,然后关闭Wi-Fi,再次请求,并且由于网络错误,任务运行完整的块并出错。它证明缓存不起作用 –

+0

它不足以预测任何事物的描述。 –

+0

你试过我的代码吗? –