使用“If-Since-Modified”标题下载文件AFNetworking

时间:2013-10-28 11:34:13

标签: ios download afnetworking

我正在尝试下载带有“Last-Modified”标头的文件。 如果文件没有被修改,我得到304就像我想要的那样,并保存重新下载文件。但是

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

如果我得到304,它会用空文件覆盖文件。

这是我的其余代码:

- (void) addPDFToDownloadQueue:(NSString *)pdf{
    if (![pdf isEqualToString:@""]) {
        NSString *urlString = [API_BASE_URL_PDF stringByAppendingPathComponent:pdf];
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                           timeoutInterval:60];
        if ([UserDefaultManager getEtagForKey:pdf]) {
            NSString *etag = [UserDefaultManager getEtagForKey:pdf];
            [request setValue:etag forHTTPHeaderField:IF_MODIFIED_SINCE];
        }
        [request setHTTPMethod: API_METHOD_GET];

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        NSString *path = [FileUtils getPathInDocumentsWithFileName:pdf] ;
        operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([operation.response respondsToSelector:@selector(allHeaderFields)]) {
                [UserDefaultManager setEtag:[operation.response.allHeaderFields objectForKey:LAST_MODIFIED] forKey:pdf];
            }
            if ([self checkIfQueueHasFinished]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DOWNLOAD_ALL_PDF_FINISHED object:nil];
            };


        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (operation.response.statusCode != RESPONSE_CODE_UP_TO_DATE) {
                LogDebug(@"%@", [error localizedDescription]);
            }
            if ([self checkIfQueueHasFinished]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DOWNLOAD_ALL_PDF_FINISHED object:nil];
            };
        }];


        [self.downloadQueue addOperation:operation];
    }

0 个答案:

没有答案