AFHTTPRequestOperation下载文件和缓存

时间:2014-08-22 10:06:16

标签: ios caching afhttprequestoperation

我使用SDWebImage框架作为很好的库,它也存储图像和缓存,

现在我也在尝试下载其他类型的文件,现在SDWebImage也没用。

我正在使用AFHTTPRequestOperation下载文件,并且正确下载,

NSURL *url = [NSURL URLWithString:@"http://mydomain/file.zip"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSString *fullPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[url lastPathComponent]];

[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]];

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    NSLog(@"bytesRead: %u, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", bytesRead, totalBytesRead, totalBytesExpectedToRead);
}];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"RES: %@", [[[operation response] allHeaderFields] description]);

    NSError *error;
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:&error];

    if (error) {
        NSLog(@"ERR: %@", [error description]);
    } else {
        NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
        long long fileSize = [fileSizeNumber longLongValue];
        NSLog(@"OK");

    }


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"ERR: %@", [error description]);
}];

[operation start];

但我想使用缓存,它总是下载而不是使用缓存, 服务器响应这样的标题:

RES: {
    "Accept-Ranges" = bytes;
    "Content-Length" = 2866793;
    "Content-Type" = "application/vnd.apple.pkpass";
    Date = "Fri, 22 Aug 2014 09:10:11 GMT";
    Etag = "\"d9c347d85aabcf1:0\"";
    "Last-Modified" = "Tue, 29 Jul 2014 18:28:08 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-Powered-By" = "ASP.NET";
}

是否有任何遗漏迫使AFHTTPRequest使用缓存? 还是有任何其他类型文件的SDWebImage库?

2 个答案:

答案 0 :(得分:0)

根据Caching on AFNetworking 2.0,您需要添加cache-control HTTP标头。

答案 1 :(得分:-1)

尝试使用此设置:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];