2017-02-28 79 views
1

我昨天在飛機上發現的用於檢查Internet連接的代碼非常慢。我在很多舊版本的SO answers中使用這種技術來檢查NSUURL,但是,如果在沒有連接的飛機上使得應用程序基本無法使用,那麼它在字面上花費了十五秒或更長的時間才返回FALSE。IOS/Objective-C:檢查Internet連接的最快方法 - 2017

是否有可以執行此操作的可靠異步方法?人們在老的答案中推薦Tony Million的可達性課程,但看起來非常複雜,蘋果公司顯然拒絕了一些應用程序using it。如果有人能夠建議在2017年檢查互聯網連接的最快,最可靠的方法,將不勝感激。謝謝。

- (BOOL)connected 
    { 
     NSURL *scriptUrl = [NSURL URLWithString:@"https://www.google.com"]; 
     NSData *data = [NSData dataWithContentsOfURL:scriptUrl]; 
     if (data) { 
      NSLog(@"Device is connected to the internet"); 
      return TRUE; 
     } 
     else { 
      NSLog(@"Device is not connected to the internet"); 
      return FALSE; 
     } 
    } 
+1

尊重爲您的測試環境租用私人飛機。有一個upvote。 – Bathsheba

+1

這是Apple自己的示例代碼。 https://developer.apple.com/library/content/samplecode/Reachability/Listings/Reachability_Reachability_h.html – Dare

+0

如何改進Xcode IDE;) – zztop

回答

3

可達纔是正確之路......即使是在2017年

所有不同的可達性類是基於蘋果的示例代碼。

它看起來很複雜,因爲它使用C API。但是用法很簡單:

- (BOOL)connected 
{ 
    Reachability *reach = [Reachability reachabilityForInternetConnection]; 

    if ([reach isReachable]) { 
     NSLog(@"Device is connected to the internet"); 
     return TRUE; 
    } 
    else { 
     NSLog(@"Device is not connected to the internet"); 
     return FALSE; 
    } 
} 

如果要使用蘋果的可達性類,而不是託尼萬元的,與[reach currentReachabilityStatus] != NotReachable更換[reach isReachable]

不要擔心蘋果可能會拒絕使用它的應用程序。如果發生這種情況,只需將類從Reachability重命名爲MyReachability即可。