30

我想要AFNetworking在 Swift 中与使用 Alamofire NetworkReachabilityManager 的 Objective-C 中类似的功能:

//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;
        }
    }
}];

我目前正在使用监听器来了解网络的状态变化

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

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

4

11 回答 11

39

网络管理器类

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

启动网络可达性观察者

@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
    }
}
于 2016-09-29T09:38:56.653 回答
19

我自己找到了答案,即只需编写一个带有闭包的侦听器,如下所述:

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()
于 2016-02-16T12:13:05.257 回答
16

这是我的实现。我在单例中使用它。请记住保留可达性管理器参考。

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()
}
于 2016-05-18T18:52:16.947 回答
9

斯威夫特 5

网络状态结构

import Foundation
import Alamofire

struct NetworkState {

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

采用: -

  if (NetworkState().isInternetAvailable) {
        // Your code here
   }
于 2019-07-16T08:00:23.790 回答
8

只要您保留对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()
}

所以你可以在你的应用程序的任何地方像这样使用它:

let networkStatus = NetworkStatus.sharedInstance

override func awakeFromNib() {
    super.awakeFromNib()
    networkStatus.startNetworkReachabilityObserver()
}

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

于 2017-06-01T06:59:14.390 回答
6

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

您可以开始使用此功能,例如:

Network().state()
于 2020-02-24T09:48:41.323 回答
3

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

这是结构网络状态:

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

以下是您在任何代码中使用它的方式:

if NetworkState().isConnected {
    // do your is Connected stuff here
}
于 2018-10-05T14:35:00.850 回答
3

如下创建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")
                      }
        })
    }
}

用法会像

@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
    }
}
于 2020-05-27T03:26:59.147 回答
2

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

如何使用:

调用NetworkReachability.shared.startListening()fromAppDelegate开始监听可达性变化

@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
    }
        
}
   
于 2020-08-10T14:16:51.107 回答
0

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

CREATE a NetworkReachabilityManagerclass fromAlamofire并配置checkNetwork()方法

import Alamofire

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

用法

switch Connectivity.checkNetwork() {
  case true:
      print("network available")
      //perform task
  case false:
      print("no network")
}
于 2020-05-14T04:13:57.547 回答
0

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

        }
     }
  }

 }
于 2021-03-24T05:03:48.823 回答