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

asp.net-web-api, cocoa, jquery, objective-c

Solution

You simply have to create an NSDictionary with your datas:

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);
}

Problem

I have a pretty basic WebAPI controller: ``` [HttpGet] public IQueryable<User> GetUsers() { return _users.AsQueryable(); } [HttpPost] public User AddUser(User toAdd) { _userRepository.AddUser(toAdd); } ``` and the User object is similarly 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, jQuery call, etc. With javascript/jquery I'd do something like : ``` var user = { "Name" : "Persons Name", "Email" : "Email@Email.com" } var processed = JSON.stringify(user); $.ajax({ url: url, data: processed, success: .... ... }); ``` I'm trying to get it to POST from Objective-C. The GET works perfectly fine, so I know it can connect etc. I've tried all kinds of things to try and get it to post an object via JSON, but I'm having no luck. Can anyone point me in the right direction? Thanks!

Original source