Send JSON data with NSURLConnection in Xcode

11,997

To send simple data in post vars to your webserver running php you simply do this in

Example

NSString * key = [NSString stringWithFormat:@"var1=%@&var2=%@&var3=%@",@"var1String" ,@"var2string" ,[NSnumber numberWithBool:YES]];

NSURL * url = [NSURL URLWithString:@"http://webserver.com/yourScriptPHP.php"];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:[key dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];
// this is for you to be able to get your server answer. 
// you will need to make your class a delegate of NSURLConnectionDelegate and NSURLConnectionDataDelegate
myClassPointerData = [[NSMutableData data] retain];

Implement

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [myClassPointerData appendData:data]
}

-(void)connection:(NSURLConnection *)connection DidFinishLoading {
    // do what you want with myClassPointerData the data that your server did send you back here
    // for info on your server php script you just need to do: echo json_encode(array('var1'=> $var1, 'var2'=>$var2...));
    // to get your server sending an answer
}
Share:
11,997
Nick
Author by

Nick

Updated on July 16, 2022

Comments

  • Nick
    Nick almost 2 years

    I am trying to send JSON data to a web server via the code below. For some reason, the request does not seem to be going out. What does it look like I am missing? Also the result from NSURLConnection (retStr) is always empty?

    NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
    
        NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
    [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];
    NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
    
  • Nicolas Manzini
    Nicolas Manzini almost 12 years
    dont forget to release your NSURLCOnnecion and your myClassPointerData