0

嗨,我正在使用此代码将 post 值发送到服务器,但我希望 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 回答