0

How to post JSON Data in synchronously way? Can use NSURLSession or AFNetworking or other way?

halfer
  • 19,824
  • 17
  • 99
  • 186
aldirc
  • 13
  • 6
  • `AFNetworking` will automatically make the request asynchronous, u just need to take the result and check for error if needed – Tj3n Dec 28 '15 at 07:58
  • sorry. i wanted to post josn in synchronously way. not asynchronously way – aldirc Dec 28 '15 at 08:09
  • @aldirc: Sorry my bad. have a look here: http://stackoverflow.com/questions/21198404/nsurlsession-with-nsblockoperation-and-queues – Anoop Vaidya Dec 28 '15 at 08:18

3 Answers3

0

Sample basic code for posting data to server using synchronous

//PASS YOUR URL HERE
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"your URL"]];


//create the Method "POST" for posting data to server
   [request setHTTPMethod:@"POST"];

//Pass The String to server like below
   NSString *strParameters =[NSString strin gWithFormat:@"user_email=%@&user_login=%@&user_pass=%@&  last_upd_by=%@&user_registered=%@&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];


//Print the data that what we send to server
   NSLog(@"the parameters are =%@", strParameters);

//Convert the String to Data
   NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];

//Apply the data to the body
   [request setHTTPBody:data1];

//Create the response and Error
   NSError *err;
   NSURLResponse *response;

   NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

   NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

//This is for Response
   NSLog(@"got response==%@", resSrt);
   if(resSrt)
   {
     NSLog(@"got response");
   }
   else
   {
     NSLog(@"faield to connect");
   }
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

In user3182143's answer, sendSynchronousRequest is deprecated in latest version iOS 9.

You can use NSURLSession

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
               NSString *strResult = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];


  }] resume];
DHEERAJ
  • 1,478
  • 12
  • 32
0

Here is my solution:

- (IBAction)postJSONSynchronization:(id)sender {

  __block BOOL success = NO;
  __block NSDictionary *jsonDic = nil;

  NSURLSession *session = [NSURLSession sharedSession];
  // 创建请求
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
  request.HTTPMethod = @"POST"; // 请求方法
  NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
  [parameters setObject:@13577766655 forKey:@"phoneNumber"];
  NSData *jsonData  = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
  request.HTTPBody = jsonData; // 请求体

  NSCondition *condition = [[NSCondition alloc] init];
  // 创建任务
  NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
      NSLog(@"Child Thread:%@",[NSThread currentThread]);
      if (!error) {
          jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
          success = YES;

      } else {
          NSLog(@"%@",error);
      }

      [condition lock];
      [condition signal];
      [condition unlock];

   }];

  [task resume];
  // 启动任务
  NSLog(@"Main Thread:%@",[NSThread currentThread]);
  [condition lock];
  [condition wait];
  [condition unlock];


  NSLog(@"测试时机");
  NSLog(@"josnDic:%@",jsonDic);}
aldirc
  • 13
  • 6
  • I also suggest that do not post JSON in sync way,because the cost of obstructing main thread is too huge! – aldirc Mar 28 '16 at 01:52