我试图在异步nsurlsession调用中调用同步nsurlsession,但它不起作用。同步呼叫没有完成。下面是密码。
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL1"]];
[request setHTTPMethod:@"GET"];
// Call first service
[[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data){
// If first webservice is successful then dont call second service
return;
}
// Call second service
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL2"]];
[request2 setHTTPMethod:@"GET"];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[[NSURLSession.sharedSession dataTaskWithRequest:request2 completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_semaphore_signal(sem);
}] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}] resume];发布于 2018-09-21 15:57:01
正如@Larme所提到的,最好在这里将一个完成块传递到您的方法中,然后在任何一个请求的完成块中调用它(看起来您希望使用来自它拥有的第一个web服务的数据,如果不是,则调用第二个):
- (void)webServiceRequestWithCompletion:(void (^_Nullable)(NSData *_Nullable completionData, NSError *_Nullable error))completionAfter {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL1"]];
[request setHTTPMethod:@"GET"];
// Call first service
[[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
// If first webservice is successful then dont call second service
if (completionAfter) {
completionAfter(data, error);
}
return;
}
// Call second service
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL2"]];
[request2 setHTTPMethod:@"GET"];
[[NSURLSession.sharedSession dataTaskWithRequest:request2 completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (completionAfter) {
completionAfter(data, error);
}
}] resume];
}] resume];
}然后你会用这样的方式称呼它:
[self webServiceRequestWithCompletion:^(NSData *completionData, NSError *error) {
// do stuff with data returned from one of the two webservices here
}];如果这不是您想要做的,那么您就需要编辑您的问题,并提供附加的上下文来说明代码是如何调用的,以及为什么您必须使用信号量(它在等待什么?)
本网站有助于理解如何使用块语法:http://goshdarnblocksyntax.com。
https://stackoverflow.com/questions/52446480
复制相似问题