2 // NetworkReachabilityManager.swift
4 // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 import SystemConfiguration
30 /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
31 /// WiFi network interfaces.
33 /// Reachability can be used to determine background information about why a network operation failed, or to retry
34 /// network requests when a connection is established. It should not be used to prevent a user from initiating a network
35 /// request, as it's possible that an initial request may be required to establish reachability.
36 public class NetworkReachabilityManager {
37 /// Defines the various states of network reachability.
39 /// - unknown: It is unknown whether the network is reachable.
40 /// - notReachable: The network is not reachable.
41 /// - reachable: The network is reachable.
42 public enum NetworkReachabilityStatus {
45 case reachable(ConnectionType)
48 /// Defines the various connection types detected by reachability flags.
50 /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
51 /// - wwan: The connection type is a WWAN connection.
52 public enum ConnectionType {
57 /// A closure executed when the network reachability status changes. The closure takes a single argument: the
58 /// network reachability status.
59 public typealias Listener = (NetworkReachabilityStatus) -> Void
63 /// Whether the network is currently reachable.
64 public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
66 /// Whether the network is currently reachable over the WWAN interface.
67 public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
69 /// Whether the network is currently reachable over Ethernet or WiFi interface.
70 public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
72 /// The current network reachability status.
73 public var networkReachabilityStatus: NetworkReachabilityStatus {
74 guard let flags = self.flags else { return .unknown }
75 return networkReachabilityStatusForFlags(flags)
78 /// The dispatch queue to execute the `listener` closure on.
79 public var listenerQueue: DispatchQueue = DispatchQueue.main
81 /// A closure executed when the network reachability status changes.
82 public var listener: Listener?
84 private var flags: SCNetworkReachabilityFlags? {
85 var flags = SCNetworkReachabilityFlags()
87 if SCNetworkReachabilityGetFlags(reachability, &flags) {
94 private let reachability: SCNetworkReachability
95 private var previousFlags: SCNetworkReachabilityFlags
97 // MARK: - Initialization
99 /// Creates a `NetworkReachabilityManager` instance with the specified host.
101 /// - parameter host: The host used to evaluate network reachability.
103 /// - returns: The new `NetworkReachabilityManager` instance.
104 public convenience init?(host: String) {
105 guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
106 self.init(reachability: reachability)
109 /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
111 /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
112 /// status of the device, both IPv4 and IPv6.
114 /// - returns: The new `NetworkReachabilityManager` instance.
115 public convenience init?() {
116 var address = sockaddr_in()
117 address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
118 address.sin_family = sa_family_t(AF_INET)
120 guard let reachability = withUnsafePointer(to: &address, { pointer in
121 return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
122 return SCNetworkReachabilityCreateWithAddress(nil, $0)
124 }) else { return nil }
126 self.init(reachability: reachability)
129 private init(reachability: SCNetworkReachability) {
130 self.reachability = reachability
131 self.previousFlags = SCNetworkReachabilityFlags()
140 /// Starts listening for changes in network reachability status.
142 /// - returns: `true` if listening was started successfully, `false` otherwise.
144 public func startListening() -> Bool {
145 var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
146 context.info = Unmanaged.passUnretained(self).toOpaque()
148 let callbackEnabled = SCNetworkReachabilitySetCallback(
150 { (_, flags, info) in
151 let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
152 reachability.notifyListener(flags)
157 let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
159 listenerQueue.async {
160 self.previousFlags = SCNetworkReachabilityFlags()
161 self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
164 return callbackEnabled && queueEnabled
167 /// Stops listening for changes in network reachability status.
168 public func stopListening() {
169 SCNetworkReachabilitySetCallback(reachability, nil, nil)
170 SCNetworkReachabilitySetDispatchQueue(reachability, nil)
173 // MARK: - Internal - Listener Notification
175 func notifyListener(_ flags: SCNetworkReachabilityFlags) {
176 guard previousFlags != flags else { return }
177 previousFlags = flags
179 listener?(networkReachabilityStatusForFlags(flags))
182 // MARK: - Internal - Network Reachability Status
184 func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
185 guard isNetworkReachable(with: flags) else { return .notReachable }
187 var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
190 if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
196 func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
197 let isReachable = flags.contains(.reachable)
198 let needsConnection = flags.contains(.connectionRequired)
199 let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
200 let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
202 return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
208 extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
210 /// Returns whether the two network reachability status values are equal.
212 /// - parameter lhs: The left-hand side value to compare.
213 /// - parameter rhs: The right-hand side value to compare.
215 /// - returns: `true` if the two values are equal, `false` otherwise.
217 lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
218 rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
222 case (.unknown, .unknown):
224 case (.notReachable, .notReachable):
226 case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
227 return lhsConnectionType == rhsConnectionType