The Ola Swift package lets you check network reachability of a named host. You can set a callback to run when the reachability of the host has changed. Ola is a simple Swift wrapper around some of Apple’s System Configuration APIs, making them easier to use.
import Foundation
import os.log
let host = "1.1.1.1"
var probe = Ola(host: host, log: .default)
probe?.activate { status in
print("host status: (\(host), \(String(describing: status)))")
}
sleep(10)
probe?.invalidate()
probe = nil
print("OK")enum OlaStatus: IntOlaStatus eumerates three boiled down host states, derived from SCNetworkReachabilityFlags.
unknownreachablecellular
class Ola: ReachingOla is the main object of this module, it implements the tiny Reaching API:
protocol Reaching {
func reach() -> OlaStatus
func reach(statusBlock: @escaping (OlaStatus) -> Void)
func activate(installing callback: @escaping (OlaStatus) -> Void) -> Bool
func invalidate()
}Each Ola object is dedicated to monitoring a specific host.
init?(host: String, log: OSLog?)hostThe name of the host to monitor.
The common use case is to synchronously—not on the main thread though QA1693—check if a given host is reachable.
func reach() -> OlaStatusReturns the reachability of the host: unknown, reachable, or cellular.
func reach(statusBlock: @escaping (OlaStatus) -> Void)Same as reach(), but non-blocking, executing on a system-provided global concurrent dispatch queues.
A less common use case is getting notified, when the state of a given host has changed. For example, to reason if it’s appropiate to issue a request.
func activate(installing callback: @escaping (OlaStatus) -> Void) -> BoolReturns true if installing the callback has been successful.
func invalidate()Invalidates the probe removing the callback.
📦 Add https://github.com/michaelnisi/ola to your package manifest.