ios 如何在 Alamofire 中使用 NetworkReachabilityManager

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35427698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:31:23  来源:igfitidea点击:

How to use NetworkReachabilityManager in Alamofire

iosswiftalamofirereachabilitynetwork-connection

提问by MuraliMohan

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

我希望AFNetworking在 Swift 中使用类似于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?

有人可以描述如何支持这些用例吗?

采纳答案by MuraliMohan

I found the answer myself i.e 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()

回答by Kirit Vaghela

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

回答by rmooney

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()
}

回答by Ammad

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 thisis a very good animation to show on your internet connection loss.

如果您的网络状态发生任何变化,您将收到通知。只是锦上添花,是一个非常好的动画,可以在您的互联网连接中断时显示。

回答by Lakhdeep Singh

SWIFT 5

快速 5

NetworkState Structure

网络状态结构

import Foundation
import Alamofire

struct NetworkState {

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

Use: -

用: -

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

回答by Karthik S

Swift 5: No need for listener object . Just we need to call the closure :

Swift 5:不需要侦听器对象。我们只需要调用闭包:

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()

回答by jonathan3087

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 postby @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.

Apple 说尽可能使用结构而不是类。所以这是我的 @rmooney 和 @Ammad 的答案版本,但使用结构而不是类。此外,我没有使用方法或函数,而是使用计算属性,我从@Abhimuralidharan 的这篇 Medium帖子中得到了这个想法。我只是将使用结构而不是类(因此您不必有单例)和使用计算属性而不是方法调用的想法放在一个解决方案中。

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
}

回答by Prakhar Prakash Bhardwaj

Solution for swift 4* + swift 5* and Alamofire 4.5+

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

CREATEa NetworkReachabilityManagerclass from Alamofireand configure the checkNetwork()method

NetworkReachabilityManager从中创建一个类Alamofire并配置该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")
}

回答by Sreeraj VR

To create NetworkManager Classas 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
    }
}