ios - POST request not receiving all json -
little issue that's been bothering me. i've been making post request aws rdb. request should return json output. issue i'm having i'll receive bytes back, contains incomplete json, converting dictionary won't work. receive null value nsdata received, can print out length of data. ideas? here's ios code requests:
#import "serviceconnector.h" @implementation serviceconnector{ nsmutabledata *receiveddata; } -(void)gettest{ //send server nsmutableurlrequest *request = [[nsmutableurlrequest alloc] initwithurl:[nsurl urlwithstring:@"my_website"]]; [request sethttpmethod:@"get"]; //initialize nsurlconnection request nsurlconnection *connection = [[nsurlconnection alloc] initwithrequest:request delegate:self]; if(!connection){ nslog(@"connection failed"); } } -(void)posttest:(nsmutablearray *)carsearches{ //build request sent server nsmutableurlrequest *request = [[nsmutableurlrequest alloc] initwithurl:[nsurl urlwithstring:@"my_website"]]; [request sethttpmethod:@"post"]; nserror *writeerror = nil; nsdata *data = [nsjsonserialization datawithjsonobject:carsearches options:nsjsonwritingprettyprinted error:&writeerror]; nsstring *jsonstring = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding]; nslog(@"json output: %@", jsonstring); [request sethttpbody:data]; //set data post body [request addvalue:[nsstring stringwithformat:@"%lu",(unsigned long)data.length] forhttpheaderfield:@"content-length"]; nsurlconnection *connection = [[nsurlconnection alloc] initwithrequest:request delegate:self]; if(!connection){ nslog(@"connection failed"); } } #pragma mark - data connection delegate - -(void)connection:(nsurlconnection *)connection didreceivedata:(nsdata *)data{ // executed when connection receives data if(!receiveddata){ receiveddata = [[nsmutabledata alloc]init]; [receiveddata appenddata:data]; } } -(void)connection:(nsurlconnection *)connection didfailwitherror:(nserror *)error{ //executed when connection fails nslog(@"connection failed error: %@",error); } -(void)connectiondidfinishloading:(nsurlconnection *)connection{ nslog(@"request complete,recieved %lu bytes of data",(unsigned long)receiveddata.length); nsstring *tmp = [nsstring stringwithutf8string:[receiveddata bytes]]; nslog(@"%@",tmp); nserror *error; nsdictionary *dictionary = [nsjsonserialization jsonobjectwithdata:[nsdata datawithbytes:[receiveddata bytes] length:[receiveddata length]] options:nsjsonreadingallowfragments error:&error]; [self.delegate requestreturneddata:dictionary]; }
in section:
if(!receiveddata){ receiveddata = [[nsmutabledata alloc]init]; [receiveddata appenddata:data]; }
you appending data if object hasn't been created yet. want append every time. if statement should read this:
if(!receiveddata){ receiveddata = [[nsmutabledata alloc]init]; } [receiveddata appenddata:data];
Comments
Post a Comment