GTNetMon 是一个轻量级的 Swift 库,用于检测设备是否已连接到互联网,识别连接类型(Wi-Fi、蜂窝网络等),并监控网络状态的变化。适用于 iOS 和 macOS。
您想要将 GTNetMon 作为 pod 使用吗?查看这里。
要将 GTNetMon
集成到您的项目中,请按照以下步骤操作
使用 GTNetMon
单例类,通过其 shared
实例访问所有公开可用的属性和方法。
可用属性如下
isConnected
:指示设备是否已连接到互联网。connectionType
:连接类型,作为 GTNetMon.ConnectionType
值(见下文)。availableConnectionTypes
:在给定时刻设备可用的连接类型集合。isExpensive
:指示设备通过蜂窝网络连接到互联网时,连接费用较高。请注意,此标志在 iOS 版本 >= 12.0 中使用时更准确。isMonitoring
:指示是否正在监控网络状态变化。除了上述属性外,还有以下两种方法
startMonitoring()
:开始监控网络状态变化。stopMonitoring()
:停止监控网络状态变化。applicationDidBecomeActive(_:)
和 applicationWillResignActive(_:)
方法中分别启动和停止监控。GTNetMonNetworkStatusChangeNotification
通知。每当发生连接变化时,就会发布此通知。在 AppDelegate.swift 文件中启动和停止监控
func applicationDidBecomeActive(_ application: UIApplication) {
GTNetMon.shared.startMonitoring()
}
func applicationWillResignActive(_ application: UIApplication) {
GTNetMon.shared.stopMonitoring()
}
一个简单的视图控制器示例实现,用于监控网络变化
import UIKit
import GTNetMon
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Observe for the GTNetMonNetworkStatusChangeNotification notification.
NotificationCenter.default.addObserver(self, selector: #selector(handleStatusChange(notification:)), name: .GTNetMonNetworkStatusChangeNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showConnectionInfo()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func handleStatusChange(notification: Notification) {
self.showConnectionInfo()
}
func showConnectionInfo() {
print("Is connected: \(GTNetMon.shared.isConnected)")
"\nAvailable Connection Types:"
for type in GTNetMon.shared.availableConnectionTypes {
print(type.toString())
}
print("\n\nCurrent Connection Type: \(GTNetMon.shared.connectionType.toString())")
print("Is Expensive: \(GTNetMon.shared.isExpensive)")
}
}
GTNetMon.ConnectionType
是一个 enum(枚举),具有以下情况
在 iOS >= 12.0 中,使用 iOS SDK 的新 Network
框架来检索网络信息。在较旧的 iOS 版本中,则使用 SCNetworkReachability
API。
当前最新版本为 1.0.3。
GTNetMon 在 MIT 许可证下获得许可。