简体   繁体   English

如何在 Alamofire 中使用 NetworkReachabilityManager

[英]How to use NetworkReachabilityManager in Alamofire

I want functionality similar to AFNetworking in Objective-C with Alamofire NetworkReachabilityManager in Swift:我想类似的功能AFNetworking在Objective-C与Alamofire NetworkReachabilityManager斯威夫特:

//Reachability detection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN: {
            [self LoadNoInternetView:NO];
            break;
        }
        case AFNetworkReachabilityStatusReachableViaWiFi: {
            [self LoadNoInternetView:NO];
            break;
        }
        case AFNetworkReachabilityStatusNotReachable: {
            break;
        }
        default: {
            break;
        }
    }
}];

I am currently using the listener to know the status changes with network我目前正在使用监听器来了解网络的状态变化

let net = NetworkReachabilityManager()
net?.startListening()

Can someone describe how to support those use cases?有人可以描述如何支持这些用例吗?

NetworkManager Class网络管理器类

class NetworkManager {

//shared instance
static let shared = NetworkManager()

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.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")

            }
        }

        // start listening
        reachabilityManager?.startListening()
   }
}

Start Network Reachability Observer启动网络可达性观察者

@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
    }
}

I found the answer myself ie by just writing a listener with closure as mentioned below:我自己找到了答案,即通过编写一个带有闭包的侦听器,如下所述:

let net = NetworkReachabilityManager()

net?.listener = { status in
    if net?.isReachable ?? false {

    switch status {

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

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

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

    case .unknown :
        print("It is unknown whether the network is reachable")

    }
}

net?.startListening()

Here's my implementation.这是我的实现。 I use it in a singleton.我在单例中使用它。 Remember to hold on to the reachability manager reference.请记住保留可达性管理器参考。

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")

func listenForReachability() {
    self.reachabilityManager?.listener = { status in
        print("Network Status Changed: \(status)")
        switch status {
        case .NotReachable:
            //Show error state
        case .Reachable(_), .Unknown:
            //Hide error state
        }
    }

    self.reachabilityManager?.startListening()
}

SWIFT 5快速 5

NetworkState Structure网络状态结构

import Foundation
import Alamofire

struct NetworkState {

    var isInternetAvailable:Bool
    {
        return NetworkReachabilityManager()!.isReachable
    }
}

Use: -用: -

  if (NetworkState().isInternetAvailable) {
        // Your code here
   }

Using a singleton is working as I long as you keep a reference of reachabilityManager只要您保留对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.只是锦上添花,是一个非常好的动画,可以在您的互联网连接中断时显示。

Swift 5: No need for listener object . Swift 5:不需要侦听器对象。 Just we need to call the closure :我们只需要调用闭包:

struct Network {

    let manager = Alamofire.NetworkReachabilityManager()

    func state() {
        manager?.startListening { status in
            switch status {
            case .notReachable :
                print("not reachable")
            case .reachable(.cellular) :
                print("cellular")
            case .reachable(.ethernetOrWiFi) :
                print("ethernetOrWiFi")
            default :
                print("unknown")
            } 
        }
    }
}

You can start using this function like :您可以开始使用此功能,例如:

Network().state()

Apple says to use a struct instead of a class when you can. Apple 说尽可能使用结构而不是类。 So here's my version of @rmooney and @Ammad 's answers, but using a struct instead of a class.所以这是我的 @rmooney 和 @Ammad 的答案版本,但使用结构而不是类。 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.此外,我没有使用方法或函数,而是使用计算属性,我从 @Abhimuralidharan 的这篇 Medium 帖子中得到了这个想法。 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
}

To create NetworkManager Class as follows ( For SWIFT 5 )如下创建NetworkManager 类对于 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
    }
}

Alamofire 5 and above Alamofire 5 及以上

import Alamofire

// MARK: NetworkReachability

final class NetworkReachability {
    
    static let shared = NetworkReachability()

    private let reachability = NetworkReachabilityManager(host: "www.apple.com")!

    typealias NetworkReachabilityStatus = NetworkReachabilityManager.NetworkReachabilityStatus

    private init() {}
    
    /// Start observing reachability changes
    func startListening() {
        reachability.startListening { [weak self] status in
            switch status {
            case .notReachable:
                self?.updateReachabilityStatus(.notReachable)
            case .reachable(let connection):
                self?.updateReachabilityStatus(.reachable(connection))
            case .unknown:
                break
            }
        }
    }
    
    /// Stop observing reachability changes
    func stopListening() {
        reachability.stopListening()
    }
    
    
    /// Updated ReachabilityStatus status based on connectivity status
    ///
    /// - Parameter status: `NetworkReachabilityStatus` enum containing reachability status
    private func updateReachabilityStatus(_ status: NetworkReachabilityStatus) {
        switch status {
        case .notReachable:
            print("Internet not available")
        case .reachable(.ethernetOrWiFi), .reachable(.cellular):
            print("Internet available")
        case .unknown:
            break
        }
    }

    /// returns current reachability status
    var isReachable: Bool {
        return reachability.isReachable
    }

    /// returns if connected via cellular
    var isConnectedViaCellular: Bool {
        return reachability.isReachableOnCellular
    }

    /// returns if connected via cellular
    var isConnectedViaWiFi: Bool {
        return reachability.isReachableOnEthernetOrWiFi
    }

    deinit {
        stopListening()
    }
}

How to use:如何使用:

Call NetworkReachability.shared.startListening() from AppDelegate to start listening for reachability changesAppDelegate调用NetworkReachability.shared.startListening()开始监听可达性变化

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
            
    var window: UIWindow?
           
            
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
             
        NetworkReachability.shared.startListening()
        
        // window and rootviewcontroller setup code
        
        return true
    }
        
}
   

Solution for swift 4* + swift 5* and Alamofire 4.5+ swift 4* + swift 5* 和 Alamofire 4.5+ 的解决方案

CREATE a NetworkReachabilityManager class from Alamofire and configure the checkNetwork() methodAlamofire创建一个NetworkReachabilityManager类并配置checkNetwork()方法

import Alamofire

class Connectivity {   
    class func checkNetwork() ->Bool {
        return NetworkReachabilityManager()!.isReachable
    }
}

USAGE用法

switch Connectivity.checkNetwork() {
  case true:
      print("network available")
      //perform task
  case false:
      print("no network")
}

Just slight Improvement in the Alamofire 5 Alamofire 5 只是略有改进

class NetworkManager {

//shared instance
static let shared = NetworkManager()

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")

func startNetworkReachabilityObserver() {
    
    reachabilityManager?.startListening { 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")

        }
     }
  }

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM