2013-12-16 41 views
0

我有以下代碼:你如何使用iPhone可達通知

- (void) testInternetConnection { 
internetConnection = [Reachability reachabilityWithHostname:@"www.google.com"]; 

// Internet is reachable 
internetConnection.reachableBlock = ^(Reachability*reach) 
{ 
    // Update the UI on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSLog(@"Yayyy, we have the interwebs!"); 
    }); 
}; 

// Internet is not reachable 
internetConnection.unreachableBlock = ^(Reachability*reach) 
{ 
    // Update the UI on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSLog(@"Someone broke the internet :("); 
    }); 
}; 

[internetConnection startNotifier]; 
} 

我如何知道我的互聯網已經使用通知改變了嗎?我理解單例方法,並在需要時使用它。

+0

是的,我正在使用該答案,但如何檢查一旦通知程序啓動? – cdub

+0

使用kReachabilityChangedNotification –

+0

並且即使當我關閉網絡時也是如此:BOOL status =([[Reachability reachabilityForInternetConnection] currentReachabilityStatus]!= NotReachable); – cdub

回答

2

嘗試儘可能在設備上測試您的代碼。

確保

BOOL status = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) 

,在設備上,如果你是在模擬器測試

模擬器只使用默認的Mac的網絡連接,因此您需要從網絡上斷開你的Mac和模擬器將經歷同樣的網絡連接損失。

感謝

0

您可以通過這個代碼檢查可達性,

//使可達性對象

reachability = [Reachability reachabilityForInternetConnection]; 

//開始通知

[reachability startNotifier]; 

//獲取到達狀態

remoteHostStatus = [reachability currentReachabilityStatus];  

謝謝。

0
//First import Reachability classes 
// In Appdelegate .h file create variables 
    Reachability *hostReach,*internetReach,*wifiReach; 
    Reachability *internetReachable; 

// After that add this code didfinish lonching with options 
internetReachable = [Reachability reachabilityForInternetConnection] ; 
[internetReachable startNotifier]; 

-(BOOL) connectedToNetwork 
{ 
const char *host_name = "www.google.com"; 
BOOL _isDataSourceAvailable = NO; 
Boolean success; 
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,host_name); 
SCNetworkReachabilityFlags flags; 
success = SCNetworkReachabilityGetFlags(reachability, &flags); 
_isDataSourceAvailable = success && 
(flags & kSCNetworkFlagsReachable) && 
!(flags & kSCNetworkFlagsConnectionRequired); 

CFRelease(reachability); 

return _isDataSourceAvailable; 
}