2017-05-09 48 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是图书馆,并且有一定的功能,以检查网络连接的情况下。你可以使用它。