5

我想在我的 iOS 应用程序启动时调用一个方法,但我只想在有连接时调用这个方法。我发现在 Objective-C 中你可以使用Reachable,但事实证明这个方法不是 Swift 的一部分。

我找到了一个名为Reachability.swift的 pod ,我正在使用提供的示例:

override func viewWillAppear(animated: Bool) {
    let reachability: Reachability
    do {
        reachability = try Reachability.reachabilityForInternetConnection()
    } catch {
        print("Unable to create Reachability")
        return
    }
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "reachabilityChanged:",
        name: ReachabilityChangedNotification,
        object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        print("This is not working.")
            return
    }
}

func reachabilityChanged(note: NSNotification) {

    let reachability = note.object as! Reachability

    if reachability.isReachable() {
        if reachability.isReachableViaWiFi() {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    } else {
        print("Not reachable")
    }
}

但是,这不能正常工作。我只在进入该 ViewController 时工作,但在打开和关闭 WiFi 时不工作。

4

1 回答 1

11

我通过声明reachability为 ViewController 的实例变量来解决这个问题:

var reachability: Reachability!

所以这个变量应该从方法中删除viewWillAppear

斯威夫特 2

override func viewWillAppear(animated: Bool) {
    do {
        reachability = try Reachability.reachabilityForInternetConnection()
    } catch {
        print("Unable to create Reachability")
        return
    }

    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "reachabilityChanged:",
        name: ReachabilityChangedNotification,
        object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        print("This is not working.")
        return
    }

}

func reachabilityChanged(note: NSNotification) {

    let reachability = note.object as! Reachability

    if reachability.isReachable() {
        if reachability.isReachableViaWiFi() {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    } else {
        print("Not reachable")
    }
}

Swift 3(由Burning提供)

var reachability: Reachability!
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    reachability = Reachability()
    NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: Notification.Name.reachabilityChanged, object: reachability)

    do {
        try reachability?.startNotifier()
    } catch {
        print("This is not working.")
        return
    }

}

func reachabilityChanged(_ note: NSNotification) {

    let reachability = note.object as! Reachability

    if reachability.connection != .none {
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    } else {
        print("Not reachable")
    }
}

这工作正常:)。

于 2015-11-23T19:22:16.257 回答