0
在這裏,我有一個非常有趣的話題討論,或者你可以說我需要一個更好的方法建議。應該首先驗證什麼 - hostReachability或netReachability?
這裏是我的代碼
+ (BOOL) isConnected
{
BOOL flag = TRUE;
if (![self isHostReachable])
{
flag = FALSE;
NSString* alertTitle= @"";
NSString* alertMessage= @"";
if (![self isInternetReachable])
{
alertTitle = @"Network unavailable";
alertMessage = @"We can't connect to the Internet. Check your settings/connection.";
}
else
{
alertTitle = @"Server not responding";
alertMessage = @"Server not responding at the moment. Please try again later. Sorry for inconvenience";
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:self
cancelButtonTitle:@"Close"
otherButtonTitles:nil];
[alert show];
}
return flag;
}
+ (BOOL) isInternetReachable
{
Reachability *netReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus netSat = [netReachability currentReachabilityStatus];
return (!(netSat == NotReachable));
}
+ (BOOL) isHostReachable
{
Reachability *hostReachability = [Reachability reachabilityWithHostname: [Connection returnHostName]];
NetworkStatus netSat = [hostReachability currentReachabilityStatus];
return (!(netSat == NotReachable));
}
在我的代碼,我習慣稱之爲「isConnected」的方法,以檢查連接狀態,問我的服務器進行數據之前。
在該方法中,我首先的檢查hostReachability。我這樣做的想法是節省計算時間。
- 如果hostReachability返回true,這意味着netConnectivity也有(無需驗證)。所以我們只用一個計算就完成了。
- 如果hostReachability返回false,那麼我檢查是它的淨連接那負責。因此兩個計算。
但它通常看到,代碼首先驗證netConnectivity,如果確定,然後驗證hostReachability。
所以大部分的時間兩次計算,與我獲得要做的事情的方式對比,多數民衆贊成。
請提出你認爲哪一個更好的方法嗎?