在iOS9之前我们可以通过 [NSURLConnection sendSynchronousRequest:request returningResponse:response error:&error]; 方法来发送同步请求数据。但在iOS9之后苹果建议废除 NSURLConnection,使用 NSURLSession 代替 NSURLConnection。
然而在最近项目中遇到了,需要使用同步请求,捣鼓一番算是找到了个人感觉不错的方式,如果有更好的方式也希望大家可以交流!
废话不多说直接上代码具体实现如下:
// 创建信号量,可以设置信号量的资源数。0表示没有资源,调用dispatch_semaphore_wait会立即等待。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"https://sample.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[sessiondata TaskWithRequest:request completionHandler:^(NSData*_Nullabledata, NSURLResponse*_Nullableresponse, NSError*_Nullableerror) {
if(!error) {
// 数据请求成功
} else {
// 数据请求失败
}
// 通知信号,如果等待线程被唤醒则返回非0,否则返回0。
dispatch_semaphore_signal(semaphore);
}] resume];
// 等待信号,可以设置超时参数。该函数返回0表示得到通知,非0表示超时。
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 执行后续操作
网友评论