ReachabilityX 使用 Apple 的 Network
框架中的 NWPathMonitor
构建,为 SwiftUI 提供了一种简单的方式来观察网络变化。
将其作为依赖项添加到您的 Package.swift
中。
dependencies: [
.package(url: "https://github.com/dscyrescotti/ReachabilityX", from: "1.0.0")
]
目前,ReachabilityX 只能通过 Swift Package Manager 安装。
ReachabilityX 包含 ReachabilityView
,它公开了从其父视图或祖先视图提供的 Reachability
对象。 当需要在多个视图中观察网络更改时,它非常方便。
首先,您需要在应用程序的入口点创建一个 Reachability
实例,以便通过 environmentObject(_:)
在多个视图之间共享它。
@main
struct TestApp: App {
@ObservedObject var reachability: Reachability = .init()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(reachability)
.onAppear {
reachability.start()
}
}
}
}
现在,您可以轻松地在 ReachabilityView
中实现您的演示逻辑,并且还可以使用 onChangeStatus(action:)
、onChangeInterfaceType(action:)
和 onChangePath(action:)
实现您的业务逻辑。
struct ContentView: View {
var body: some View {
ReachabilityView { (status: Status) in
// some presentation logic
}
.onChangeStatus { status in
// some business logic associated with status changes
}
.onChangeInterfaceType { interfaceType in
// some business logic associated with interface type changes
}
.onChangePath { path in
// some business logic associated with path changes
}
}
}
ReachabilityView
提供了一些初始化器,允许您使用带有不同参数的闭包来构建您想要的视图。
// use it when you are only interested in status
ReachabilityView { (status: Status) in
// some presentation logic associated with status changes
}
// use it when you are only interested in interface type
ReachabilityView { (interfaceType: InterfaceType) in
// some presentation logic associated with interface changes
}
// use it when you are interested in both of status and interface type
ReachabilityView { (status: Status, interfaceType: InterfaceType) in
// some presentation logic associated with status and interface type changes
}
// use it when you need to know the whole network path object
ReachabilityView { (path: NWPath) in
// some presentation logic associated with network path
}
ReachabiliyX 还允许您通过在 SwiftUI 视图中声明来创建自己的 Reachability
实例,以观察网络变化。
struct ContentView: View {
@StateObject var reachability: Reachability = .init()
var body: some View {
Group {
switch reachability.status {
case .satisfied: Text("Connected!")
default: Text("Not Connected!")
}
}
.onAppear {
reachability.start()
}
.onDisappear {
reachability.stop()
}
.onChangeInterfaceType(reachability) { interfaceType in
// some business logic
}
}
}
要获取网络路径更新,您需要调用 start()
方法以开始观察网络变化。 如果您想停止观察更改,则必须调用 stop()
方法。 这将不再监视任何网络变化。
Dscyre Scotti (@dscyrescotti)
欢迎所有开发者贡献 ReachabilityX,如果您有任何改进的想法,或者发现任何类型的错误,请提交 issue。
ReachabilityX 基于 MIT 许可证可用。 有关更多信息,请参见 LICENSE 文件。