ios - how to right way in call webservice with json and without json in iphone? -
i have included 2 way of webservice have not sure way right or worng
1)with json
//create 2 class variable nsmutabledata *receiveddata; nsurlconnection *firstconnection; nsmutabledictionary *userdata=[[nsmutabledictionary alloc]init]; //add data in userdata nsdictionary *senddata=[nsdictionary dictionarywithobject:userdata forkey:@"data"]; nserror *error; nsdata *jsondata = [nsjsonserialization datawithjsonobject:senddata options:kniloptions error:&error]; nsstring *urlstring=@"www.example.com/user_register.php"; nsurl *url = [nsurl urlwithstring:urlstring]; nsmutableurlrequest *req = [nsmutableurlrequest requestwithurl:url]; [req setvalue:@"application/json" forhttpheaderfield:@"accept"]; [req setvalue:@"application/json" forhttpheaderfield:@"content-type"]; [req setvalue:[nsstring stringwithformat:@"%d", [jsondata length]] forhttpheaderfield:@"content-length"]; [req sethttpmethod:@"post"]; [req sethttpbody:jsondata]; receiveddata = [[nsmutabledata alloc]init]; firstconnection=[nsurlconnection connectionwithrequest:req delegate:self]; if(!firstconnection){ receiveddata=nil; }
after have created 3 method handle request
- (void)connection:(nsurlconnection *)connection didreceiveresponse:(nsurlresponse *)response{ // response code } - (void)connection:(nsurlconnection *)connection didreceivedata:(nsdata *)data{ //get response data [receiveddata appenddata:data]; } - (void)connection:(nsurlconnection *)connection didfailwitherror:(nserror *)error { // if connection fail } - (void)connectiondidfinishloading:(nsurlconnection *)connection { nserror *errorjson=nil; //received data convert disctionary nsmutabledictionary *datadistionary=[nsjsonserialization jsonobjectwithdata:receiveddata options:kniloptions error:&errorjson]; }
i have received server data
2) without json
nsstring *url=[nsstring stringwithformat:@"www.example.com/get_hotels.php?city_id=%d",cityid]; nsurl *myurl = [nsurl urlwithstring:url]; nsurlrequest *myrequest = [nsurlrequest requestwithurl:myurl]; theconnection=[nsurlconnection connectionwithrequest:myrequest delegate:self]; if(!theconnection){ receiveddata=nil; } - (void)connection:(nsurlconnection *)connection didreceiveresponse:(nsurlresponse *)response{ // response code } - (void)connection:(nsurlconnection *)connection didreceivedata:(nsdata *)data{ //get response data [receiveddata appenddata:data]; } - (void)connection:(nsurlconnection *)connection didfailwitherror:(nserror *)error { // if connection fail } - (void)connectiondidfinishloading:(nsurlconnection *)connection { nserror *errorjson=nil; //received data convert disctionary nsmutabledictionary *datadistionary=[nsjsonserialization jsonobjectwithdata:receiveddata options:kniloptions error:&errorjson]; }
they 2 way work other way json parsing have no idea please can us
Comments
Post a Comment