簡體   English   中英

如何檢測是否沒有互聯網連接

[英]How to detect if there no internet connection

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

Apple為您提供Reachability類,並將其添加到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];

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

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的可用性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM