0

I'm trying to upload a multipart image to server where image is converted to NSData and this NSdata is sent a parameter in HTTP body in a JSON string. Unfortunately the app crashes with this message:

**'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'**

I understand that the problem is with JSON. The sample code:

-(void) uploadmultipartimage {

    NSString * urlimageupload = [NSString stringWithFormat:@"%@api/mobile_profiles/avatar_upload",URLPrefixCertintell];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlimageupload]];

    NSData *imageData = UIImageJPEGRepresentation(_profileimage, 1.0);

    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:60];
    [request setHTTPMethod:@"PUT"];

    NSString *boundary = @"unique-consistent-string";

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    // post body
    NSMutableData *body = [NSMutableData data];

    // add params (all params are strings)
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n", @"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];

    // add image data
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=imageName.jpg\r\n", @"imageFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    NSDictionary *jsonString = @{@"user":@{@"user_token":[[NSUserDefaults standardUserDefaults] stringForKey:@"user_token"]},@"api_key":APIKey,@"profile":body};

    //***Code Crashes here**//
    NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:nil];

    //
    // setting the body of the post to the reqeust
    [request setHTTPBody:postData];

    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if(data.length > 0) {
            //success
        }
    }];

}
QED
  • 9,803
  • 7
  • 50
  • 87
Suraj K Thomas
  • 5,773
  • 4
  • 52
  • 64
  • 1
    Have you seen [this question](http://stackoverflow.com/questions/1443158/binary-data-in-json-string-something-better-than-base64)? – trojanfoe Feb 17 '16 at 17:59

1 Answers1

1

You need to convert your data to NSString:

    NSString *g=[[NSUserDefaults standardUserDefaults] stringForKey:@"user_token"];
if (!g) 
    g=@"Default Token";

NSString *base64Body = [body base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSDictionary *jsonString = @{@"user":@{@"user_token":g},@"api_key":APIKey,@"profile":base64Body};

Then you can always argue about the possibility of nil when reading the "user_token".

Take care,

/Anders.

Anders Cedronius
  • 2,036
  • 1
  • 23
  • 29