1. 程式人生 > >iOS開發實時監測網路狀態Reachability

iOS開發實時監測網路狀態Reachability

1.首先在AppDelegate.h新增標頭檔案"Reachability.h",匯入框架SystemConfiguration.framework。Reachability自己網上找。

2. 在AppDelegate.m中這樣實現:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//開啟網路狀況的監聽
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    hostReach = [Reachability reachabilityForInternetConnection];
//    hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];//可以以多種形式初始化
   [hostReach startNotifier];  //開始監聽,會啟動一個run loop
    [self updateInterfaceWithReachability: hostReach];
}
//監聽到網路狀態改變
- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability: curReach];
}

//處理連線改變後的情況
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    //對連線改變做出響應的處理動作。
    NetworkStatus status = [curReach currentReachabilityStatus];
    if(status == ReachableViaWWAN)
    {
        printf("\n3g/2G\n");
    }
    else if(status == ReachableViaWiFi)
    {
        printf("\nwifi\n");
    }else
    {
        printf("\n無網路\n");
    }
    
}

當網路連線狀態發生改變的時候會發出通知,hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];

這麼初始化會出現一個問題,就是網路改變的時候通知會走兩次,可以改成這樣初始化:hostReach = [Reachability reachabilityForInternetConnection];除錯用真機測試,模擬器可能會出現不準確的情況。這是蘋果提供的網路判斷下面說一下AFNetworking的:
- (BOOL)checkNetworkStatus {
    
    __block BOOL isNetworkUse = YES;
    
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusUnknown) {
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWWAN){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusNotReachable){
            // 網路異常操作
            isNetworkUse = NO;
            XLLog(@"網路異常,請檢查網路是否可用!");
        }
    }];
    [reachabilityManager startMonitoring];
    return isNetworkUse;
}
在AppDelegate 中匯入AF的標頭檔案 ,在didFinishLaunchingWithOptions 方法中呼叫就可以了,
記得[reachabilityManager startMonitoring];用法很簡單不多說了以上所述是小編給大家介紹的iOS 檢測網路狀態的兩種方法,
希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。