在将值发布到服务器之前显示HUD

时间:2014-03-11 01:15:17

标签: ios objective-c request hud

您好我正在使用此代码将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);

1 个答案:

答案 0 :(得分: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

    });

});