3

我正在尝试下载带有“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];
    }
4

0 回答 0