AFHTTPRequestOperation 下载文件即使服务器 return 错误

AFHTTPRequestOperation download file even when server return error

我是 Objective-c 的新人,我想向服务器发送带有令牌的 URL 请求以下载文件。如果令牌无效,服务器将 return HTTP 500 错误。

但是我遇到了一个问题,即使操作return错误,文件仍然被创建,但是文件的内容是错误信息。 我的期望是当操作出错时,不应创建和下载文件。抱歉解释不当...

下面是我的代码。

- (void)attemptResourceFileWithToken:(NSString*)token
                            from:(NSString*)url
                              to:(NSString*)targetPath
               completionHandler:(void (^)(NSError*))handler {

//create an NSURL object, which is used to make an NSURLRequest.
NSString *string = [NSString stringWithFormat:@"%@&token=%@", url, token];
NSURL *requestUrl = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
DLog(@"Request URL: %@", requestUrl);

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

[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:targetPath append:NO]];
DLog(@"Target file path: %@", targetPath);

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    DLog(@"Successfully get the response from server");
    handler(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    DLog(@"ERR: %@", [error description]);
    handler(error);
}];

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    DLog(@"Downloading %ld of %lld bytes", (long) totalBytesRead, totalBytesExpectedToRead);
}];

[operation start];

}

  1. setOutputStream 将文件保存到目标路径。
  2. 如果操作成功完成,处理程序return nil
  3. 如果操作失败,return错误。

我能做什么,如果 3(操作失败),那么第 1 步 setOutputSteam 将取消或不保存文件。

您得到的结果是预期的,因为 outputStream 就像一个临时缓冲区。来自官方文档:

The output stream that is used to write data received until the request is finished.

By default, data is accumulated into a buffer that is stored into responseData upon completion of the request, with the intermediary outputStream property set to nil. When outputStream is set, the data will not be accumulated into an internal buffer, and as a result, the responseData property of the completed request will be nil. The output stream will be scheduled in the network thread runloop upon being set.

您应该做的是将outputStream 生成的文件视为临时文件。在你的成功回调中,你应该将它移动到一个更永久的位置(并且可能重命名它)。在错误回调中你可以简单地删除它。

备选方案是根本不设置 outputStream 并尝试保存 responseObject。我不在我的 PC ATM 上,所以我现在还不能给你任何关于该解决方案的提示。

这是一个与您类似的问题,请注意已接受答案中的评论 - link