您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 網路狀態偵測:用 Reachability 判斷 WIFI 與行動網路

編輯:iOS 開發綜合

網路應用有必要隨時掌握使用者的連線狀態,原因有兩個:一是讓使用者明白「現在是網路問題,不是 App 壞了」;二是依連線品質做聰明決策,替使用者省流量。

典型的策略是:WIFI 環境下載高清圖,行動網路只抓縮圖,完全沒有網路時就顯示離線快取內容。

Reachability 的使用步驟

蘋果官方提供了 Reachability 這個範例程式,是偵測網路狀態最省事的方式:
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

步驟三項:

1. 加入框架 SystemConfiguration.framework。

2. 加入原始碼 Reachability.h 與 Reachability.m。

3. 引入標頭

#import "Reachability.h"

封裝成工具類

// NetworkTool.h
@interface NetworkTool : NSObject
+ (BOOL)isEnableWIFI;
+ (BOOL)isEnable3G;
@end

// NetworkTool.m
#import "NetworkTool.h"
#import "Reachability.h"

@implementation NetworkTool

+ (BOOL)isEnableWIFI {
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

+ (BOOL)isEnable3G {
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

@end

持續監控網路變化

若要即時反應網路切換,則需註冊通知並啟動 notifier:

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(reachabilityChanged:)
                                                name:kReachabilityChangedNotification
                                              object:nil];

    self.netReachability = [Reachability reachabilityForInternetConnection];
    [self.netReachability startNotifier];
}

- (void)dealloc {
    [self.netReachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kReachabilityChangedNotification
                                                  object:nil];
}

完整實例

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(networkStateChange)
                                                name:kReachabilityChangedNotification
                                              object:nil];
    self.reachability = [Reachability reachabilityForInternetConnection];
    [self.reachability startNotifier];
}

- (void)dealloc {
    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self checkNetworkState];
}

#pragma mark - 網路類型改變時呼叫

- (void)networkStateChange {
    if ([NetworkTool isEnableWIFI]) {
        [[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
                                    message:@"您現在的網路環境為 WIFI!開始暢享吧!"
                                   delegate:self
                          cancelButtonTitle:@"確定"
                          otherButtonTitles:nil] show];
    } else if ([NetworkTool isEnable3G]) {
        [[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
                                    message:@"您現在的網路環境為 3G/4G!"
                                   delegate:self
                          cancelButtonTitle:@"確定"
                          otherButtonTitles:nil] show];
    } else {
        [[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
                                    message:@"您目前沒有可連的網路或已經離線!"
                                   delegate:self
                          cancelButtonTitle:@"確定"
                          otherButtonTitles:nil] show];
    }
}

@end

幾個實務提醒

Reachability 判斷的是「有沒有可達的路徑」,而不是「網路品質好不好」。使用者連上咖啡廳 WIFI 但沒有對外網路時,reachabilityForLocalWiFi 仍會回報可達,因此關鍵請求還是要靠 timeout 與失敗重試來把關。

另外,Reachability 已被官方標記為 deprecated,新專案建議改用 NWPathMonitor(Network 框架)。它只需要幾行就能完成同樣的事,而且能同時取得介面型別(WIFI/蜂巢式/有線)與串流狀態:

let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
    if path.status == .satisfied {
        // 依 path.usesInterfaceType(.wifi) 判斷連線方式
    }
}
monitor.start(queue: DispatchQueue(label: "NetworkMonitor"))

最後,網路狀態變化的通知可能來得相當頻繁(例如行動網路在基地台間切換)。若每收到一次通知就跳提示框,使用者會被洗版。實務上應加上 debounce 或只在「狀態等級真正改變」時才更新 UI。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved