web-dev-qa-db-fra.com

Comment utiliser NetworkReachabilityManager dans Alamofire

Je souhaite une fonctionnalité similaire à AFNetworking dans Objective-C avec Alamofire NetworkReachabilityManager dans Swift:

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

J'utilise actuellement l'auditeur pour connaître les changements d'état avec le réseau

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

Quelqu'un peut-il décrire comment prendre en charge ces cas d'utilisation?

16
MuraliMohan

J'ai trouvé la réponse moi-même, c'est-à-dire simplement en écrivant un auditeur à fermeture comme mentionné ci-dessous: 

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

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

    }
}
16
MuraliMohan

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

Démarrer l'observabilité de l'accessibilité au réseau

@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
    }
}
28
Kirit Vaghela

Voici ma mise en œuvre. Je l'utilise dans un singleton. N'oubliez pas de conserver la référence du gestionnaire d'accessibilité.

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

Utiliser un singleton fonctionne aussi longtemps que vous gardez une référence de 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()
}

Vous pouvez donc l'utiliser comme ceci n'importe où dans votre application:

let networkStatus = NetworkStatus.sharedInstance

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

Vous serez informé de tout changement dans l'état de votre réseau. Juste pour la cerise sur le gâteau ceci est une très bonne animation à montrer sur votre perte de connexion Internet.

6
Ammad

Apple dit d'utiliser une structure plutôt qu'une classe quand vous le pouvez. Voici donc ma version de @rmooney et les réponses de @Ammad, mais en utilisant une structure plutôt qu'une classe. De plus, au lieu d’utiliser une méthode ou une fonction, j’utilise une propriété calculée et j’ai eu cette idée de ce Medium post de @Abhimuralidharan. Je ne fais que mettre à la fois l'idée d'utiliser une structure au lieu d'une classe (vous n'avez donc pas besoin d'un singleton) et d'utiliser une propriété calculée au lieu d'un appel de méthode dans une solution.

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

Voici comment vous l'utilisez dans l'un de vos codes:

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