Nandu Kathmandi
Nandu Kathmandi

Reputation: 21

How do I POST JSON data object to server iOS8?

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 8. 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:

How can I send the below format to server???

 {"createFrom":"","createType":"","filename":"AC","filter":"","lstData":[{"FieldName":"LNK_RELATED_CN","FieldValue":""},{"FieldName":"LNK_RELATED_CO","FieldValue":""},{"FieldName":"MLS_PURPOSE","FieldValue":"Inquiry"},{"FieldName":"MLS_STATUS","FieldValue":"Open"},{"FieldName":"MMO_NOTES","FieldValue":""},{"FieldName":"DTE_NEXTACTIONDATE","FieldValue":""},{"FieldName":"MMO_NEXTACTION","FieldValue":""}],"password":"Infodat2","username":"manmeets","IsNew":true}

I have seen code like this:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@AssetSave",[defaults objectForKey:@"siteAddress"]]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];
_responseData = [NSMutableData data];
NSLog(@"request : %@", request);
_nsurlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

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?

Upvotes: 0

Views: 297

Answers (1)

Wain
Wain

Reputation: 119031

The code you have is fine, you just need to create jsonData:

jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

(thought you should really also include an &error so you can see what's happening if something goes wrong)

Upvotes: 1

Related Questions