当AFNetworking收到304 - ETag时返回200

时间:2013-08-06 09:41:11

标签: ios caching afnetworking etag

我想使用etag来缓存我的图像,第一次下载所有图像时应该这样,但是当第二次它应该以304进入失败的块时也是如此。

我已尝试在外部提出请求,我得到的就像我应该的那样,只是AFNetworking我遇到了麻烦

   NSString *urlString = [API_BASE_URL_PHOTOS stringByAppendingPathComponent:[photo getPathToPhoto]];
    NSString *properlyEscapedURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:properlyEscapedURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if ([UserDefaultManager getEtagForKey:photo.nom] != nil) {
        [request setValue:[UserDefaultManager getEtagForKey:photo.nom] forHTTPHeaderField:ETAG_IF_NONE_MATCH];
    } 
    [request setHTTPMethod:API_METHOD_GET];

AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

    [FileUtils createDirectoryInDocumentsWithFileName:photo.folderName];
    NSString *docPath = [FileUtils getPathInDocumentsWithFileName:[photo getPathToPhoto]];

    // Save Image
    NSData *imageData = UIImageJPEGRepresentation(image, 90);
    [imageData writeToFile:docPath atomically:YES];


    if ([response respondsToSelector:@selector(allHeaderFields)]) {
        NSDictionary *allHeaderFields = [response allHeaderFields];
        [UserDefaultManager setEtag:[allHeaderFields objectForKey:ETAG] forKey:photo.nom];
    }


    if ([[DownloadManager sharedManager].downloadQueue.operations count] == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DOWNLOAD_ALL_PHOTOS_FINISHED object:nil];
    }
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    if (response.statusCode != RESPONSE_CODE_PHOTO_UP_TO_DATE) {
        LogDebug(@"%@", [error localizedDescription]);
    }

}];

1 个答案:

答案 0 :(得分:6)

我设法通过将我的请求更改为

来解决此问题
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                           timeoutInterval:60];

希望这有助于