swift-reachability

1.1.0

Network reachability based on Apple's "NWPathMonitor"
mihai8804858/swift-reachability

What's New

1.1.0

2024-03-01T23:44:17Z

What's Changed

  • Add Combine support

Full Changelog: 1.0.0...1.1.0

SwiftReachability

Network reachability based on Apple's NWPathMonitor.

CI

Installation

You can add swift-reachability to an Xcode project by adding it to your project as a package.

https://github.com/mihai8804858/swift-reachability

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"),

Quick Start

  • Create an instance of Reachability, or use the provided Reachability.shared instance:
private let reachability = Reachability.shared
  • Check the connection status:
let isConnected = reachability.status.isConnected
let isDisconnected = reachability.status.isDisconnected
switch 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.isExpensive

Whether 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")
    }
  }
}

License

This library is released under the MIT license. See LICENSE for details.

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sat Apr 27 2024 02:21:14 GMT-0900 (Hawaii-Aleutian Daylight Time)