Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Image upload via AFNetworking 2.0

I've been looking examples for the new AFNetworking 2.0 to upload images. But I'm hitting wall and couldn't figure out what's wrong with the code. So this is the code I used

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://myserverurl.com"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

TIA

like image 566
ordinaryman09 Avatar asked Oct 09 '13 01:10

ordinaryman09


1 Answers

I ended up using the multi-part request

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFormData:imageData name:@"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
like image 79
ordinaryman09 Avatar answered Nov 02 '22 23:11

ordinaryman09