Network reachability based on Apple's NWPathMonitor.
You can add swift-reachability to an Xcode project by adding it to your project as a package.
If you want to use swift-reachability in a SwiftPM project, it's as
simple as adding it to your Package.swift:
dependencies: [
.package(url: "https://github.com/mihai8804858/swift-reachability", from: "1.0.0")
]And then adding the product to any target that needs access to the library:
.product(name: "SwiftReachability", package: "swift-reachability"),- Create an instance of
Reachability, or use the providedReachability.sharedinstance:
private let reachability = Reachability.shared- Check the connection status:
let isConnected = reachability.status.isConnectedlet isDisconnected = reachability.status.isDisconnectedswitch reachability.status {
case .connected(let connectionType):
...
case .disconnected(let reason):
...
}- Check the connection type:
switch reachability.status.connectionType {
#if os(iOS)
case .cellular(_):
...
#endif
case .wifi:
...
case .wiredEthernet:
...
case .loopback:
...
case .unknown:
...
}See ConnectionStatus, ConnectionType and DisconnectedReason for more info.
- Check network constraints:
Whether the path uses an interface that is considered expensive, such as Cellular or a Personal Hotspot.
let isExpensive = reachability.isExpensiveWhether the path uses an interface in Low Data Mode.
let isConstrained = reachability.isConstrained- Listen for changes:
for await status in networkReachability.changes() {
...
}for await isExpensive in networkReachability.expensiveChanges() {
...
}for await isConstrained in networkReachability.constrainedChanges() {
...
}- SwiftUI Support
Reachability conforms to ObservableObject so it can be easily integrated into SwiftUI View and automatically update the UI when status changes:
struct ContentView: View {
@ObservedObject private var reachability = Reachability.shared
var body: some View {
switch reachability.status {
case .connected: Text("Connected")
case .disconnected: Text("Disconnected")
}
}
}This library is released under the MIT license. See LICENSE for details.