我是iOS开发新手。我已经搜索并尝试了几种方法,但程序不想等待异步调用完成。Objective C - 如何等待异步调用完成
调试时,函数CheckForHost首先返回-1作为retVal。这会导致调用函数的方法继续。稍后,程序返回到CheckForHost函数,将正确的值设置为retVal。我也试过用NSCondition,但没有运气要么...
有人可以告诉我我做错了什么或应该做不同吗?非常感谢您的帮助!
下面的代码:
-(int)CheckForHost
{
InternetActive = -1;
HostActive = -1;
dispatch_queue_t myQueue = dispatch_queue_create("my queue", NULL);
__block int retVal = -1;
dispatch_async(myQueue, ^{
[self HostInit];
dispatch_async(dispatch_get_main_queue(), ^{
[internetReachable stopNotifier];
[hostReachable stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (InternetActive == 0) {
retVal = 0;
} else if (HostActive == 0) {
retVal = 1;
} else
retVal = 2;
});
});
return retVal;
}
-(void)HostInit
{
// check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
[hostReachable startNotifier];
// now patiently wait for the notification
}
-(void)checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
InternetActive = 0;
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
InternetActive = 1;
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
InternetActive = 1;
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
HostActive = 0;
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
HostActive = 1;
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
HostActive = 1;
break;
}
}
}
你打这个电话的线程是什么?你永远不要在UI线程中等待。使用某种完成处理程序。 –