Migrating ASIHTTPRequest to AFNetworking (uploading a PNG to a web service)
For part 2 of my AFNetworking migration experiences, let’s cover uploading a file to a web service.
Here is the original code:
NSString *ws = [NSString stringWithFormat:@"http://myurl.com?id=%@", theID]; NSURL *url = [NSURL URLWithString:ws]; NSData *postData = [[[NSData alloc] initWithContentsOfFile:filePath] autorelease]; ASIFormDataRequest *request; request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease]; [request setPostValue:pictureFileName forKey:@"file"]; [request setData:postData withFileName:pictureFileName andContentType:@"image/png" forKey:@"file"]; [request setRequestMethod:@"POST"]; [request setShouldAttemptPersistentConnection:YES]; [request setUploadProgressDelegate:progressView]; [request setCompletionBlock:^{ NSLog(@"success with response string %@", request.responseString); }]; [request setFailedBlock:^{ NSLog(@"error: %@", request.error.localizedDescription); }]; [request startAsynchronous]; |
And here is the AFNetworking code:
NSString *ws = [NSString stringWithFormat:@"http://myurl.com?id=%@", theID]; NSURL *url = [NSURL URLWithString:ws]; NSData *postData = [[[NSData alloc] initWithContentsOfFile:filePath] autorelease]; NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:postData forKey:@"file"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:sendDictionary constructingBodyWithBlock:^(id < AFMultipartFormData > formData) { [formData appendPartWithFileData:postData name:pictureFileName fileName:pictureFileName mimeType:@"image/png"]; } ]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { if (totalBytesExpectedToWrite == 0) { progressView.progress = 0.0; } else { progressView.progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite; } }]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"success with response string %@", operation.responseString); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error: %@", error.localizedDescription); }]; [operation start]; |
The AFNetworking code is somewhat longer, so that is a bit of a problem. If anyone has any suggestions on how to make the AFNetworking code a bit more concise, please let me know.
BTW, Happy Birthday to Joe Don Baker, a distinguished actor with such outstanding films to his credit such as Mitchell, Final Justice, Fletch, and of course the all-time classic, Joysticks.