4

我正在尝试使用 etag 来缓存我的图像,第一次它应该下载所有图像,但是第二次它也应该使用 304 进入失败的块。

我已经尝试在外部提出请求,但我得到了 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]);
    }

}];
4

1 回答 1

6

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

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                           timeoutInterval:60];

希望这会有所帮助

于 2013-08-07T08:22:38.870 回答