1. 程式人生 > >檢測網路狀態(Stackoverflow)

檢測網路狀態(Stackoverflow)

檢查網路 轉自Stackoverflow原文連線http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-iphone-sdk

METHOD 1: Use a simple (ARC and GCD compatible) class to do it

//方法一用ARC和GCD來做

1) Add SystemConfiguration framework to the project but don't worry about including it anywhere

//在工程中新增SystemConfiguration庫

2) Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)

//把Reachability.h和Reachability.m檔案新增進來(可以從github連線上下載)

3) Update the interface section

//修改標頭檔案

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end

4) Then implement this method in the .m file of your view controller which you can call

//修改實現檔案,(別用google了 用百度吧.)

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.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
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };

    [internetReachableFoo startNotifier];
}

METHOD 2: Do it yourself the old way using Apple's outdated Reachability class

//用蘋果原來的Reachability類來實現

1) Add SystemConfiguration framework to the project but don't worry about including it anywhere

//新增SystemConfiguration庫

2) Add Apple's version of Reachability.h and Reachability.m to the project (you can get those here)

//把Reachability.h和Reachability.m檔案新增進來

3) Add @class Reachability; to the .h file of where you are implementing the code

//在你要實現程式碼的.h檔案宣告@class Reachability;

4) Create a couple instances to check in the interface section of the .h file:

//在.h中實現兩個屬性

Reachability* internetReachable;
Reachability* hostReachable;

5) Add a method in the .h for when the network status updates:

//.h新增方法

-(void) checkNetworkStatus:(NSNotification *)notice;

6) Add #import "Reachability.h" to the .m file where you are implementing the check

//在實現檔案匯入標頭檔案

7) In the .m file of where you are implementing the check, you can place this in one of the first methods called (init or viewWillAppear or viewDidLoad etc):

//在實現檔案實現檢測網路的方法,第一次檢測可以放在(init or viewWillAppear or viewDidLoad )方法裡

-(void) viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}

8) Set up the method for when the notification gets sent and set whatever checks or call whatever methods you may have set up (in my case, I just set a BOOL)

//實現通知執行的方法當收到通知的時候會執行該方法,可以用一個bool值來判斷網路狀態

-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;
        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;
        }
    }
}

9) In your dealloc or viewWillDisappear or similar method, remove yourself as an observer

//在dealloc or viewWillDisappear中銷燬通知

-(void) viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note: There might be an instance using viewWillDisappear where you receive a memory warning and the observer never gets unregistered so you should account for that as well.

Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects like ShareKit. If this happens, you'll have to rename one of the pairs of Reachability.h and Reachability.m files to something else to resolve the issue.//Reachability類是比較常用的類,如果飲用了別的庫,發現重名衝突,你可以把類檔案的名字改了,或者找一些其他方法解決這個問題.