Search code examples
phpiosmysqlafnetworking-2

AFNetworking 2.0 multipart/form-data upload to mySQL


I have tried many things but I can't seem to get it working. I can upload text through a UITextField to the mySQL database and I can upload an image through UIImageView separately but when I try to put them together it does not work:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
NSDictionary *parameters = @{@"new": self.enter};
NSData *imageData = UIImageJPEGRepresentation(self.uploadImage.image, 0.5);
[manager POST:@"http://emily-ip.com/write.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imageData name:@"image" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

This code gives me the error:

"The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fabeb081660 

So I put this in:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

This uploads the image but does not upload the text entered from the text field and this is the output I get:

Success: <4572726f 72>
Success: <53756363 65737366 756c>

I have looked at so many posts but I can't find the problem. I think it is with the text field anyway. Can someone please help me fix the code?


Solution

  • I have figured it out. This is to post an image and text from a textfield and UIImageVIew:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"new": self.enter.text};
    NSData *imageData = UIImageJPEGRepresentation(self.uploadImage.image, 0.5);
    [manager POST:@"http://emily-ip.com/write.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                [formData appendPartWithFileData:imageData name:@"image" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];