Majkeli Majkeli - 2 years ago 87
Objective-C Question

Need example for Posting Core Data objects in JSON to RESTful web service

I've been reading over code samples and posts for days but I haven't found a definitive way to post JSON data from my Core Data objects to a RESTful web service. There's a TON of documentation about pulling the JSON from a web service but not so much about sending stuff back. Can anyone point me to a good example or post some code on how to do it? I'm using Core Data and I have the object I want to send back mapped to a Dictionary but I'm missing the code to send it to the service.


I ended up with the code below which looks right and runs without errors, but I get 0 bytes of data returned and my webservice doesn't seem to be receiving the request. The JSON data looks good, the URL is correct, and I can hit the webservice and get JSON data back from it. The NSURLConnection delegate methods also fire as expected.

Is there anything I'm missing below?

- (void)SubmitSystems
NSFetchRequest * allSystems = [[NSFetchRequest alloc] init];
[allSystems setEntity:[NSEntityDescription entityForName:@"System" inManagedObjectContext:self.managedObjectContext]];
NSError * error = nil;
NSArray * systems = [self.managedObjectContext executeFetchRequest:allSystems error:&error];

//error handling goes here
//for (NSManagedObject * system in systems) {

NSManagedObject *system = systems[2];

NSString *entityString = @"System";
NSString * serverString = [NSString stringWithFormat:@"%@%@", kWebServiceAddress, entityString];
NSURL *url = [NSURL URLWithString:serverString];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:[self jsonSystemDictionary:(System *)system] options:kNilOptions error:&error];

//NSLog([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); //debug only

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30.f];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];

self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


Answer Source

You're going to need to NSMutableURLRequest. Using this, you can use setHTTPMethod and pass it the @"POST" string, and then use the attributes of your NSManagedObject to populate the URL, HTTPBody and/or HTTPHeader as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download