2012-03-22 110 views
0

如何檢測何時沒有互聯網連接。或者連接超時。 我正在使用NSURLConnection類。如何檢測是否沒有互聯網連接

+1

您可以使用'Reachability'類作爲解釋:?如何使用可達性類檢測有效的互聯網連接(http://stackoverflow.com/questions/5195012/how-to-use-可達性 - 類 - 檢測 - 有效 - 因特網連接) – sch 2012-03-22 20:46:16

+1

重複的:http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-iphone- SDK – 2012-03-22 20:57:53

回答

0

檢查互聯網連接的最簡單方法是使用以下代碼。

NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; 
NSString *result = [[NSString alloc] init]; 
result = (URLString != NULL) ? @"Yes" : @"No"; 
NSLog(@"Internet connection availability : %@", result); 

但是這個代碼必須依靠google.com

1

蘋果爲您提供一流的可達性的可用性,這增加ypur項目。導入Reachability.h和Reachability.m文件。添加systemConfiguration框架的工作。並在代碼中添加以下代碼片段。

Reachability *internetReachableinst; 
internetReachableinst= [Reachability reachabilityWithHostName:@"www.google.com"]; 
internetReachableinst.reachableBlock = ^(Reachability*reach) 
    { 

     // Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      NSLog(@"Internet is connected"); 
     }); 
    }; 

    //Internet is not reachable 
    internetReachableinst.unreachableBlock = ^(Reachability*reach) 
    { 

     //Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      NSLog(@"No internet"); 
     }); 
    }; 
    [internetReachableinst startNotifier];