Search code examples
iosafnetworking-2

image upload using AFNetworking, ios


I have to upload image to server by sending bytes of photo and I'm using AFNetworking,
but I keep getting this error-

Error: Error Domain=NSCocoaErrorDomain Code=3840 "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=0x10abb7350 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}


Solution

  • If the PHP server is not responding with application/json, then you have to tell your manager to accept general HTTP responses:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:imageFilename mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Success: %@", string);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    

    If you server is responding with JSON response, then perhaps it's not setting the Content-Type header properly, e.g., header("Content-type: application/json");.