How to use NetworkReachabilityManager in Alamofire

前端 未结 10 1431
醉酒成梦
醉酒成梦 2020-12-02 14:31

I want functionality similar to AFNetworking in Objective-C with Alamofire NetworkReachabilityManager in Swift:

//Reachability detection
[[AFNet         


        
10条回答
  •  庸人自扰
    2020-12-02 15:21

    Using a singleton is working as I long as you keep a reference of reachabilityManager

    class NetworkStatus {
    static let sharedInstance = NetworkStatus()
    
    private init() {}
    
    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
    
    func startNetworkReachabilityObserver() {
        reachabilityManager?.listener = { status in
    
            switch status {
    
            case .notReachable:
                print("The network is not reachable")
    
            case .unknown :
                print("It is unknown whether the network is reachable")
    
            case .reachable(.ethernetOrWiFi):
                print("The network is reachable over the WiFi connection")
    
            case .reachable(.wwan):
                print("The network is reachable over the WWAN connection")
    
            }
        }
        reachabilityManager?.startListening()
    }
    

    So you can use it like this anywhere in your app:

    let networkStatus = NetworkStatus.sharedInstance
    
    override func awakeFromNib() {
        super.awakeFromNib()
        networkStatus.startNetworkReachabilityObserver()
    }
    

    You will be notified of any change in your network status. Just for icing on the cake this is a very good animation to show on your internet connection loss.

提交回复
热议问题