Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I POST JSON data object to server in iOS5?

I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 5. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...

The first steps I took to try and solve the problem looked as follows:

    //build an info object and convert to json
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];

    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:someURLSetBefore];
    [request setHTTPMethod:@"POST"];
    // any other things to set in request? or working this way?

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // What to do with NSURLConnection? Or how to send differently?

But I really don't know how to send a JSON object to a server using a POST method at all. Could anybody please help me out?

like image 457
CGee Avatar asked Jul 11 '12 14:07

CGee


1 Answers

I worked it out by trying a bit around, here's my code:

    //build an info object and convert to json
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];

    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:someURLSetBefore];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:jsonData];

    // print json:
    NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
                                                     encoding:NSUTF8StringEncoding]);
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
like image 138
CGee Avatar answered Oct 06 '22 23:10

CGee