0

サーバーから結果を取得するために次のコードを使用しています

        NSString *queryString = @"MyString"

        NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];

        NSLog(@"%@",response);

        if (err != nil)
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Error"
                                                           message: @"An error has occurred. Kindly check your internet connection"
                                                          delegate: self
                                                 cancelButtonTitle:@"Ok"
                                                 otherButtonTitles:nil];
            [alert show];
            [indicator stopAnimating];
        }
        else
        {
//BLABLA
}

このコードの問題は、サーバーが遅延を示し、この応答を取得するのに 3 秒かかる場合です。

NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] 

3 秒間、iPhone の画面が動かなくなりました。モバイルの速度が低下したりジャムしたりしないように、バックグラウンドで実行するにはどうすればよいですか

よろしく

4

2 に答える 2

1

あなたがしているのは、メインスレッドから HTTP リクエストを送信することです。あなたが言ったように、それはUIを詰まらせます。バックグラウンド スレッドを生成し、サーバーにリクエストを送信する必要があります。応答が戻ってきたら、メイン スレッドから UI を更新する必要があります。これは、UI コーディングの一般的なパターンです。

__block__  NSString *response;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    //your server url and request. data comes back in this background thread
    response; = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];

    dispatch_async(dispatch_get_main_queue(), ^{
        //update main thread here.
        NSLog(@"%@",response);

        if (err != nil)
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Error"
                                                           message: @"An error has occurred."
                                                          delegate: self
                                                 cancelButtonTitle:@"Ok"
                                                 otherButtonTitles:nil];
            [alert show];
            [indicator stopAnimating];
        }
    });
});

を使用して新しいスレッドを生成することもできますperformSelectorInBackground:withObject:。実行されたセレクターは、新しいスレッドの自動解放プール、実行ループ、およびその他の構成の詳細を設定する役割を果たします。Apple のThreading Programming Guideの「Using NSObject to Spawn a Thread」を参照してください。

上で投稿したように、Grand Central Dispatchを使用した方がよいでしょう。GCD は新しいテクノロジであり、メモリ オーバーヘッドとコード行の点でより効率的です。

于 2013-01-23T08:22:42.737 に答える
-1

情報の取得と送信に私のお気に入りであるASIHTTPRequestを使用できます。

于 2013-01-23T08:23:45.410 に答える