gpt4 book ai didi

ios - 如何在不阻塞主线程的情况下等待网络调用在 iOS 上返回数据?

转载 作者:行者123 更新时间:2023-11-28 18:09:13 25 4
gpt4 key购买 nike

当我的 iOS 应用程序启动时,我需要从我的服务器获取一些关键设置(例如:http://www.example.com/critical_app_settings.php)。我需要在加载用户数据之前获取此数据。

进行此调用的正确方法是什么,基本上是“暂停”应用程序,但仍不阻塞主线程并保持良好的合规性?

目前我正在做这个例子,这显然是不正确的,因为它完全阻止了一切:

NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: myURLString]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody:myRequestData];
NSURLResponse *response;
NSError *error;
NSString *returnString = [[NSString alloc] init];

returnString = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error]
encoding: NSASCIIStringEncoding];

最佳答案

您可以使用 NSURLSessionDataTask 而不是使用 NSURLConnection sendSynchronousRequest。另外 sendSynchronousRequest 已从 iOS 9 中弃用。代码如下

NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: myURLString]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody:myRequestData];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ([httpResponse statusCode]==200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString* returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//do whatever operations necessary on main thread
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
//action on failure
});
}
}];
[dataTask resume];

因为它是异步操作,所以你的主线程不会被阻塞。就暂停应用程序而言,您可以在调用电话之前显示某种事件指示器或禁用用户交互。一旦响应到来,隐藏指示器或启用 UI。

关于ios - 如何在不阻塞主线程的情况下等待网络调用在 iOS 上返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138247/

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