2017-05-09 49 views
5

我需要一個函數才能在系統檢測到沒有互聯網連接時運行,然後在系統檢測到互聯網連接時運行另一個函數。如何檢測iOS上的互聯網連接更改,委託樣式?

我在想是這樣的:

func onInternetConnection() { 
    //Enable actions 
} 

func onInternetDisconnection() { 
    //Disable actions, alert user 
} 

我還需要一種方式,當系統被重新連接進行檢測,這樣我就可以讓用戶知道它的重新連接,就像在Facebook的使者。

我該怎麼做?

我爲我的網絡層使用Moya/Alamofire。

+0

阿拉莫菲爾包含網絡可達性,閱讀關於它[這裏](https://github.com/Alamofire/Alamofire#network-reachability),它使用塊,有點比代表 – Tj3n

+0

看看答案[這裏](http://stackoverflow.com/questions/25398664/check-for-internet-connection-availability-in-swift) –

+0

檢查[此lib](https://github.com/ashleymills/Reachability.swift#example ---關閉),當互聯網連接狀態改變時,它會觸發關閉。 – Toldy

回答

3

這個作品在Alamofire

import Alamofire 

// In your view did load or in app delegate do like this 
let reachabilityManager = NetworkReachabilityManager() 
reachabilityManager.listener = { status in 

    switch status { 

    case .notReachable: 
    print("The network is not reachable") 
    self.onInternetDisconnection() 

    case .unknown : 
    print("It is unknown whether the network is reachable") 
    self.onInternetDisconnection() // not sure what to do for this case 

    case .reachable(.ethernetOrWiFi): 
    print("The network is reachable over the WiFi connection") 
    self.onInternetConnection() 

    case .reachable(.wwan): 
    print("The network is reachable over the WWAN connection") 
    self.onInternetConnection() 

    } 
} 
+0

我可以在哪裏放置這個'reachabilityManager'? – Berry

+0

你可以使它成爲應用程序委託或某個單例的實例變量。 –

+0

沒有Alamofire和本地的任何方式做到這一點? – toast

0

Alamofire和Rechability是圖書館,並且有一定的功能,以檢查網絡連接的情況下。你可以使用它。