2

ユーザーが入力した資格情報がバックエンドシステムで検証されるログインモジュールを構築しています。非同期呼び出しを使用して資格情報を検証しています。ユーザーが認証されたら、メソッドを使用して次の画面に進みますpresentViewController:animated:completion。問題は、presentViewControllerメソッドの起動に次の画面が表示されるまでに時間がかかることです。私の以前の呼び出しは、sendAsynchronousRequest:request queue:queue completionHandler: どういうわけか副作用を引き起こしているのではないかと心配しています。

念のために言っておきますが、4〜6秒は、コマンドpresentViewController:animated:completionが開始されてからです。コードをデバッグし、メソッドが呼び出された瞬間を監視しているためです。

最初に:NSURLConnectionメソッドが呼び出されます:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)

2番目:UIViewControllerメソッドは異常な時間をかけて実行されていると呼ばれます

UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"];

[self presentViewController:firstViewController animated:YES completion:nil];

どんな助けでも大歓迎です。

ありがとう、マルコス。

4

1 に答える 1

12

これは、バックグラウンドスレッドからUIを操作する典型的な症状です。UIKitメインスレッドのメソッドのみを呼び出すようにする必要があります。完了ハンドラーは特定のスレッドで呼び出されることが保証されていないため、次のようにする必要があります。

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"];
        [self presentViewController:firstViewController animated:YES completion:nil];
    });
}

これにより、コードがメインスレッドで実行されることが保証されます。

于 2013-02-26T00:40:29.443 に答える