Posting data to .NET WebAPI from objective-C / cocoa

I have a pretty simple WebAPI controller:

[HttpGet] public IQueryable<User> GetUsers() { return _users.AsQueryable(); } [HttpPost] public User AddUser(User toAdd) { _userRepository.AddUser(toAdd); } 

and the User object is also simple:

 public class User { public String name { get; set; } public String email { get; set; } } 

(obviously, some of the boring parts are left out!)

Posting to the service works fine through a C # call, a jQuery call, etc.

With javascript / jquery, I would do something like:

 var user = { "Name" : "Persons Name", "Email" : " Email@Email.com " } var processed = JSON.stringify(user); $.ajax({ url: url, data: processed, success: .... ... }); 

I am trying to get it on POST with Objective-C. GET works fine, so I know that it can connect, etc.

I tried all kinds of things to try to get it to publish the object via JSON, but I had no luck. Can someone point me in the right direction?

Thanks!

+4
source share
1 answer

You just need to create an NSDictionary with your data:

 NSDictionary *postDict = [[NSDictionary alloc] initWithObjectsAndKeys: @"Person Name", @"Name", @" Email@Email.com ", @"Email", nil]; 

Then convert it to NSData and create your request

 NSError *error = nil; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:kNilOptions error:&error]; NSURLResponse *response; NSData *localData = nil; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:yourUrl]]; [request setHTTPMethod:@"POST"]; 

And finally send your request to the server:

 if (error == nil) { [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPBody:jsonData]; // Send the request and get the response localData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *result = [[NSString alloc] initWithData:localData encoding:NSASCIIStringEncoding]; NSLog(@"Post result : %@", result); } 
+3
source

Source: https://habr.com/ru/post/1497311/


All Articles