网络检测器 1.0.0

网络检测器 1.0.0

Spyros Zarzonis维护。



网络检测器

Version License Platform

描述

NetworkDetector是一个非常简单的iOS、macOS和tvOS库,用于检测网络变化,并根据网络状态调用闭包或广播通知。NetworkDetector使用iOS 12中引入的NWPathMonitor作为底层,旨在消除多年来使用的Reachability类的使用。这个库灵感来源于Ashley Mills的Reachability.swift,虽然底层使用NWPathMonitor,但使用方法类似。

安装

NetworkDetector通过CocoaPods提供。要安装它,只需将以下行添加到您的Podfile中:

pod 'NetworkDetector'

示例

此仓库包含iOS、macOS和tvOS的示例项目。要运行示例项目,首先克隆仓库,然后从Example目录中运行pod install

用法

闭包

注意:所有闭包都在主队列上执行。

//declare this property where it won't go out of scope relative to your listener
let networkDetector = NetworkDetector()

networkDetector.reachableHandler = {
    print("Internet connection is active")
}

networkDetector.unreachableHandler = {
    print("Internet connection is down")
}

do {
    try networkDetector.startMonitoring()
} catch let error {
    print(error.localizedDescription)
}

以及停止监控

networkDetector.stopMonitoring()

通知

注意:所有通知都在主队列上传递。

//declare this property where it won't go out of scope relative to your listener
let networkDetector = NetworkDetector()

NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: .networkStatusChanged, object: networkDetector)

do {
    try networkDetector.startMonitoring()
} catch let error {
    print(error.localizedDescription)
}

以及

@objc private func networkStatusChanged(_ note: Notification) {
    let networkDetector = note.object as! NetworkDetector

    switch networkDetector.connection {
        case .reachable:
            print("The network is reachable")
        case .none:
            print("Network not reachable")
    }
}

以及停止监控

networkDetector.stopMonitoring()

要求

  • iOS 12
  • macOS 10.14
  • tvOS 12
  • Swift 4.2

想要帮忙吗?

如果您修复了错误,或添加了新功能,非常欢迎您创建一个拉取请求。

作者

Spyros Zarzonis,[email protected]

许可证

NetworkDetector可以在MIT许可证下使用。更多信息请参阅LICENSE文件。