0

こんにちは、私はこのコードを使用して投稿値をサーバーに送信していますが、リクエストが終了したときにのみ表示されるため、リクエストが実行されている間に HUD を表示したいと考えています。

-(IBAction)sendk:(id)sender {
/*HUD*/

        SLHUD *hudView = [SLHUD Mostrar:self.view]; // Creates a Hud object.
        hudView.text = @"Please Wait"; // Sets the text of the Hud.
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        activityIndicator.alpha = 1.0;
        activityIndicator.center = CGPointMake(160, 280);
        activityIndicator.hidesWhenStopped = NO;
        [activityIndicator setTag:899];
        [self.view addSubview:activityIndicator];
        [activityIndicator startAnimating];
        /*FIN HUD*/

        NSString *post =[[NSString alloc] initWithFormat:@"user=%@&pass=%@",[username text],[password text]];

        NSLog(@"%@",post);
        NSURL *url=[NSURL URLWithString:@"URL TO SERVER"];

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

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"%ld",(long)[response statusCode]);

        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        NSLog(@"%@",responseData);
4

1 に答える 1

1

問題は、ネットワーク リクエストが完了するまでコードがメイン スレッドをブロックしていることです。画面はメソッドが返された後にのみ更新されsendkますが、メソッドはメソッドが終了するまで返されませんsendSynchronousRequest。解決策は、ネットワーク コード ( の後のすべて/*FIN HUD*/) をバックグラウンド スレッドにディスパッチするかsendAsynchronousRequest、 を使用し、完了ブロックを使用して、応答が到着したときにメイン スレッドに通知することです。

バックグラウンド スレッドを使用するためのコード フレームワークは次のようになります。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

    // do networking stuff here

    dispatch_async( dispatch_get_main_queue(), ^{

        // turn off the HUD and remove the spinner here
        // also do something with the network response here

    });

});
于 2014-03-11T01:26:30.690 に答える