How to use NetworkReachabilityManager in Alamofire

前端 未结 10 1445
醉酒成梦
醉酒成梦 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:14

    To create NetworkManager Class as follows (For SWIFT 5)

    import UIKit
    import Alamofire
    class NetworkManager {
        static let shared = NetworkManager()
        let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
        func startNetworkReachabilityObserver() {
            reachabilityManager?.startListening(onUpdatePerforming: { 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(.cellular):
                                    print("The network is reachable over the cellular connection")
                          }
            })
        }
    }
    

    And the usage will be like

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            // add network reachability observer on app start
            NetworkManager.shared.startNetworkReachabilityObserver()
    
            return true
        }
    }
    

提交回复
热议问题