如何在Alamofire中使用NetworkReachabilityManager

问题描述 投票:19回答:5

我希望在Objective-C中使用类似于AFNetworking的功能与Swift中的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;
        }
    }
}];

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

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

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

ios swift alamofire reachability network-connection
5个回答
33
投票

NetworkManager类

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

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

18
投票

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

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

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

7
投票

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

您将收到有关网络状态变化的通知。只是为了锦上添花this是一个非常好的动画,以显示您的互联网连接丢失。


1
投票

Apple表示尽可能使用结构而不是类。所以这是我的@rmooney版本和@Ammad的答案,但使用的是结构而不是类。另外,我没有使用方法或函数,而是使用计算属性,我从@Abhimuralidharan的这个中型post得到了这个想法。我只是提出使用结构而不是类的想法(所以你不必有一个单例)并在一个解决方案中使用计算属性而不是方法调用。

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

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

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

1
投票

SWIFT 5

NetworkState结构

import Foundation
import Alamofire

struct NetworkState {

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

使用: -

  if (NetworkState().isInternetAvailable) {
        // Your code here
   }
© www.soinside.com 2019 - 2024. All rights reserved.