2017-04-06 122 views
2

我正在使用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自己找到它。如果發現讀取其他請求。

回答

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

我按步驟運行應用程序。我首先請求並退出文件,然後關閉Wi-Fi,再次請求,並且由於網絡錯誤,任務運行完整的塊並出錯。它證明緩存不起作用 –

+0

它不足以預測任何事物的描述。 –

+0

你試過我的代碼嗎? –