×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Objective-C
Posted by: Black Light
Added: Mar 3, 2013 12:11 PM
Views: 33
Tags: no tags
response in the form of String, JSON Array, JSON Object
  1. NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@webservice.php", kServerName]];
  2.            
  3.             NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
  4.             [urlRequest setHTTPMethod:@"POST"];
  5.             NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];
  6.            
  7.             [urlRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
  8.            
  9.             // setup post string
  10.             NSMutableString *postString = [[NSMutableString alloc] init];
  11.             [postString appendFormat:@"&param1=%@", param1];
  12.             [postString appendFormat:@"&param2=%@", param2];
  13.             [postString appendFormat:@"&param3=%d", param3];
  14.            
  15.             [urlRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
  16.            
  17.             NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  18.            
  19.             [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
  20.                 if ([data length] >0 && error == nil)
  21.                 {
  22.                     // if response is a string
  23.                     NSString *responseString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  24.  
  25. // if response is JSON Array
  26.  NSMutableArray *array=[NSMutableArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
  27.                    
  28. // if response is JSON Object
  29.  NSMutableDictionary *dictionary=[NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
  30.                 }
  31.                 else if ([data length] == 0 && error == nil)
  32.                 {
  33.                     NSLog(@"Nothing was downloaded.");
  34.                 }
  35.                 else if (error != nil)
  36.                 {
  37.                     NSLog(@"Error happened = %@", error);
  38.                 }
  39.             }];
  40.