How to use NetworkReachabilityManager in Alamofire

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

    Apple says to use a struct instead of a class when you can. So here's my version of @rmooney and @Ammad 's answers, but using a struct instead of a class. Additionally, instead of using a method or function, I am using a computed property and I got that idea from this Medium post by @Abhimuralidharan. I'm just putting both the idea of using a struct instead of a class (so you don't have to have a singleton) and using a computed property instead of a method call together in one solution.

    Here's the struct NetworkState:

    import Foundation
    import Alamofire
    
    struct NetworkState {
    
        var isConnected: Bool {
            // isReachable checks for wwan, ethernet, and wifi, if
            // you only want 1 or 2 of these, the change the .isReachable
            // at the end to one of the other options.
            return NetworkReachabilityManager(host: www.apple.com)!.isReachable
        }
    }
    

    Here is how you use it in any of your code:

    if NetworkState().isConnected {
        // do your is Connected stuff here
    }
    

提交回复
热议问题