jquery - Posting data to .NET WebAPI from objective-C/cocoa -
i have pretty basic webapi controller:
[httpget] public iqueryable<user> getusers() { return _users.asqueryable(); } [httppost] public user adduser(user toadd) { _userrepository.adduser(toadd); }
and user object simple:
public class user { public string name { get; set; } public string email { get; set; } }
(obviously of boring parts left out!)
posting service works fine through c# call, jquery call, etc.
with javascript/jquery i'd :
var user = { "name" : "persons name", "email" : "email@email.com" } var processed = json.stringify(user); $.ajax({ url: url, data: processed, success: .... ... });
i'm trying post objective-c. works fine, know can connect etc.
i've tried kinds of things try , post object via json, i'm having no luck. can point me in right direction?
thanks!
you have create nsdictionary datas:
nsdictionary *postdict = [[nsdictionary alloc] initwithobjectsandkeys: @"person name", @"name", @"email@email.com", @"email", nil];
then, convert nsdata , create 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 request server:
if (error == nil) { [request setvalue:@"application/json" forhttpheaderfield:@"content-type"]; [request setvalue:@"application/json" forhttpheaderfield:@"accept"]; [request sethttpbody:jsondata]; // send request , response localdata = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&error]; nsstring *result = [[nsstring alloc] initwithdata:localdata encoding:nsasciistringencoding]; nslog(@"post result : %@", result); }
Comments
Post a Comment