I'm new in Objective-c, I want to send a URL request with token to server to download the file. If token is invalid, server will return HTTP 500 error.
But I got one problem was that even operation return error, the file still been created, but the file's content is the error msg. my expectation is when operation get error, the file should not be created and downloaded. sry for poor explanation...
below is my code.
- (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 will save the file to the target path.
- if operation completed successfully, handler return nil
- if operation failed, return error.
what I can do so that if 3 (operation fail) then step 1 setOutputSteam will cancel or don't save the file.