6

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

0

1 Answer 1

34

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);
}];
6
  • 3
    appendPartWithFileData:imageData name:@"image" error:nil] is not working anymore, I guess. You should use: [formData appendPartWithFormData:imageData name:@"image"]; ...but still it doesn't work for me :/
    – raistlin
    Nov 7, 2013 at 14:43
  • 4
    and why do you even bother with fileURl if you're not using it after?
    – raistlin
    Nov 7, 2013 at 14:44
  • 2
    @raistlin appendPartWithFileData worked for me as well. see stackoverflow.com/a/20190352/1933185
    – jerik
    Nov 25, 2013 at 10:59
  • 2
    @raistlin I think you mean "filePath," which indeed does not seem to be used here. May 24, 2014 at 5:25
  • @ordinaryman09 do u know how to add Header values with an image?
    – Ushan87
    Jan 29, 2015 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.