2017-06-23 15 views
-2

私のアプリでPOSTリクエストを作成します。私は次のコードを使用します:objective-c - NSUrlConnectionがiOSでアプリをクラッシュさせるX

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]; 

これをiOS 9デバイス搭載のシミュレータで実行すると、完全に動作します。しかし、iOS Xを搭載したiPadでは、リクエストを実行するたびにクラッシュします。

POST iOS Xデバイスで動作させるにはどうすればよいですか?

kEmailLoginは、JSONを返すサービスの場合はHTTPSというURLの変数です。

+0

エラーが発生した場合、エラーメッセージは何ですか? 'sendSynchronousRequest:'は非推奨ですか?とrecommanded(現在のスレッドをブロックし、それがメインスレッドの場合はUIをブロックする)?また、 'error'をalloc/initしないでください。 – Larme

+0

@Larmeエラーメッセージは表示されません。私はiPadでデバッグできません –

+0

コンソールにエラーメッセージがありませんか? 「EXC_BAD_ACCESS」や「SIG_ABRT」などはありませんか? – Larme

答えて

0

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]; 
関連する問題