我是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線程中等待。使用某種完成處理程序。 –