-2

I want to make a POST request in my app. I use the following code:

NSString *post = [NSString stringWithFormat:@"Email=%@&Password=%@",self.emailTxt.text,self.pwTxt.text];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:kEmailLogin]];

[request setHTTPMethod:@"POST"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

When I run this with the simulator with an iOS 9 device it works perfectly. But in my iPad with iOS X it crashes every time I perform the request.

How should I do the POST request to make it work in a iOS X device?

kEmailLogin is a variable with a HTTPS url for a service that returns a JSON.

Piyush
  • 1,534
  • 12
  • 32
O.D.
  • 57
  • 9
  • If it crash, what's the error message? Do you know that `sendSynchronousRequest:` is deprecated? And not recommanded (blocking current thread, and if it's the main thread, block the UI)? Also, do no alloc/init the `error`. – Larme Jun 23 '17 at 10:25
  • @Larme I don't have error message. I can't debug with my iPad – O.D. Jun 23 '17 at 10:32
  • You don't have an error message in console? You don't have a "EXC_BAD_ACCESS" or "SIG_ABRT" or something like that? – Larme Jun 23 '17 at 10:33
  • @Larme I can't debug with my IPad, because I have to update Xcode and I can't yet. In my iPad the app crashes with no error message. – O.D. Jun 23 '17 at 10:54

1 Answers1

1

I have solved this issue using NSURLSession.

NSString *post = [NSString stringWithFormat:@"Email=%@&Password=%@",self.emailTxt.text,self.pwTxt.text];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:kEmailLogin];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPBody = [post dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPMethod = @"POST";

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;  
}];
[postDataTask resume];
O.D.
  • 57
  • 9