我是 Objective-c 的新手,我想向服务器发送一个带有令牌的 URL 请求以下载文件。如果令牌无效,服务器将返回 HTTP 500 错误。
但是我遇到的一个问题是即使操作返回错误,文件仍然被创建,但文件的内容是错误消息。我的期望是当操作出错时,不应该创建和下载文件。抱歉解释不佳...
下面是我的代码。
- (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];
}
- setOutputStream 将文件保存到目标路径。
- 如果操作成功完成,处理程序返回 nil
- 如果操作失败,返回错误。
我能做什么,如果 3(操作失败)那么第 1 步 setOutputSteam 将取消或不保存文件。