ios - 如何检测 iPhone 是否刚刚连接到互联网?

标签 ios iphone swift wifi

一旦设备连接到 wifi,我需要在我的应用程序中做一些事情。它不是关于“它连接到 wifi 了吗?”,而是“告诉我设备何时连接到 wifi,而之前它是离线的?”

换句话说,当 iPhone 以任何方式连接到互联网时,我需要响应事件。

AFNetworking 或自定义 API 是否可行?

最佳答案

您可以使用 Reachability .

在示例代码中您会发现:

import UIKit

let useClosures = false

class ViewController: UIViewController {

    @IBOutlet weak var networkStatus: UILabel!

    let reachability = Reachability.reachabilityForInternetConnection()

    override func viewDidLoad() {
        super.viewDidLoad()

        if (useClosures) {
            reachability?.whenReachable = { reachability in
                self.updateLabelColourWhenReachable(reachability)
            }
            reachability?.whenUnreachable = { reachability in
                self.updateLabelColourWhenNotReachable(reachability)
            }
        } else {
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
        }

        reachability?.startNotifier()

        // Initial reachability check
        if let reachability = reachability {
            if reachability.isReachable() {
                updateLabelColourWhenReachable(reachability)
            } else {
                updateLabelColourWhenNotReachable(reachability)
            }
        }
    }

    deinit {

        reachability?.stopNotifier()

        if (!useClosures) {
            NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
        }
    }

    func updateLabelColourWhenReachable(reachability: Reachability) {
        if reachability.isReachableViaWiFi() {
            self.networkStatus.textColor = UIColor.greenColor()
        } else {
            self.networkStatus.textColor = UIColor.blueColor()
        }

        self.networkStatus.text = reachability.currentReachabilityString
    }

    func updateLabelColourWhenNotReachable(reachability: Reachability) {
        self.networkStatus.textColor = UIColor.redColor()

        self.networkStatus.text = reachability.currentReachabilityString
    }


    func reachabilityChanged(note: NSNotification) {
        let reachability = note.object as! Reachability

        if reachability.isReachable() {
            updateLabelColourWhenReachable(reachability)
        } else {
            updateLabelColourWhenNotReachable(reachability)
        }
    }
}

关于ios - 如何检测 iPhone 是否刚刚连接到互联网?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32905132/

相关文章:

iphone - libarchive 解压到指定文件夹?

iPhone 应用程序开发 - 将一个 View 加载到另一个 View 中

ios - 如何更改 JSON key 名称 Swift?

ios - ViewController 中的 UICollectionView 中拉动刷新

ios - Swift Cocoa Touch 自定义单元格为 IBOutlets 返回 nil

ios - UImenucontroller Action 使用委托(delegate)来设置 tableView 正在编辑不工作_swift

iphone - 如何在获取请求时调试核心数据崩溃

ios - 刷新UI TableView

ios - 我如何在核心数据中保存图像然后检索它?使用 swift

ios - EXPO app 出现在 iOS 上时闪烁,但 Android 没问题。它是由 EXPO 自动创建的( react 导航)