gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:10:21 25 4
gpt4 key购买 nike

您好,我正在使用此代码将发布值发送到服务器,但我希望 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);

最佳答案

问题是代码阻塞主线程直到网络请求完成。屏幕只会在 sendk 方法返回后更新,但该方法不会返回,直到 sendSynchronousRequest 方法完成。解决方案是将网络代码(/*FIN HUD*/ 之后的所有内容)调度到后台线程,或者使用sendAsynchronousRequest,并使用完成 block 通知主线程响应到达时线程。

使用后台线程的代码框架如下所示

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

});

});

关于ios - 在将值发布到服务器之前显示 HUD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22314578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com