0%

[swift] NetWork (3) 判斷手機是否有網路連線可用

主要參考兩篇文章做修改:
Detect Internet status programmatically using Swift and Object-C language
[iOS] 即時判斷網路連線狀態 (Detect Network Status on Real-Time)

  • Apple已經用Objective-C寫了判斷網路的套件給大家使用,所以接下來會解說如何用Swift專案載入Objective-C套件
  • 先到這邊下載Reachability
  • 接著把Reachability專案中的Reachability.m和Reachability.h抓到專案中
  • 在專案中新增Header檔

  • 打開Header檔,把Reachability.h掛進去,這樣以後專案中引用Reachability裡面的class都不再Import了
  • 把Header檔加到專案的Build Setting中
  • 打開Reachability.m找到(void)dealloc改成 ```swift
  • (void)dealloc
    {
    [self stopNotifier];
    if (_reachabilityRef != NULL)
    {
    CFRelease(_reachabilityRef);
    }
    [super dealloc];
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

* 到專案中的Build Phases,把Reachability.m加上-fno-objc-arc [![](http://1.bp.blogspot.com/-iCs_Qc3MS_g/VPfP4egfeoI/AAAAAAAAEfg/loz5m7jQjpU/s400/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-05%2B%E4%B8%8A%E5%8D%8811.38.54.png)](http://1.bp.blogspot.com/-iCs_Qc3MS_g/VPfP4egfeoI/AAAAAAAAEfg/loz5m7jQjpU/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-05%2B%E4%B8%8A%E5%8D%8811.38.54.png)
* 以上就全部掛載完成了,接著來看看這個套件如何使用,並讓它告知我們網路狀態
打開view controller,新增一個監測網路的變數,並且在viewDidLoad寫下 ```swift
var internetReachability:Reachability!; //網路狀態監控
override func viewDidLoad() {
super.viewDidLoad()
//在通知中心註冊事件,當網路狀態有變動的時候會觸發
NSNotificationCenter.defaultCenter().addObserverForName(kReachabilityChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in
let networksStatus: NetworkStatus = self.internetReachability.currentReachabilityStatus()
var status: String!
if networksStatus.value == 0 {
status = "Disconnection"
} else if networksStatus.value == 1 {
status = "Connection"
} else {
status = "Connection"
}
UIAlertView(title: "網路狀態", message: status, delegate: nil, cancelButtonTitle: "OK").show();
}
self.internetReachability = Reachability.reachabilityForInternetConnection();
//開始監控狀況
self.internetReachability.startNotifier()
}

在Mac上面執行看看,測試方法就是把mac的wifi連線給關閉,就會看到App跳出提示訊息了

  • 接下來把viewDidLoad改成如下,這段是告訴你目前使用的網路是什麼?Wifi or 3G之類的 ```swift
    override func viewDidLoad() {
      super.viewDidLoad()
      let statusReach: Reachability = Reachability.reachabilityForInternetConnection()
      let networksStatus: NetworkStatus = statusReach.currentReachabilityStatus()
      var status: String!
      if networksStatus.value == 0 {
          status = "NoReachable"
      } else if networksStatus.value == 1 {
          status = "ReachableViaWiFi"
      } else {
          status = "ReachableViaWWAN"
      }
      UIAlertView(title: "網路狀態", message: status, delegate: nil, cancelButtonTitle: "OK").show();
    
    }

```
執行看看