NetworkReachabilityManager.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. //
  2. // NetworkReachabilityManager.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  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:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  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
  22. // THE SOFTWARE.
  23. //
  24. #if !(os(watchOS) || os(Linux) || os(Windows))
  25. import Foundation
  26. import SystemConfiguration
  27. /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and
  28. /// WiFi network interfaces.
  29. ///
  30. /// Reachability can be used to determine background information about why a network operation failed, or to retry
  31. /// network requests when a connection is established. It should not be used to prevent a user from initiating a network
  32. /// request, as it's possible that an initial request may be required to establish reachability.
  33. open class NetworkReachabilityManager {
  34. /// Defines the various states of network reachability.
  35. public enum NetworkReachabilityStatus {
  36. /// It is unknown whether the network is reachable.
  37. case unknown
  38. /// The network is not reachable.
  39. case notReachable
  40. /// The network is reachable on the associated `ConnectionType`.
  41. case reachable(ConnectionType)
  42. init(_ flags: SCNetworkReachabilityFlags) {
  43. guard flags.isActuallyReachable else { self = .notReachable; return }
  44. var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
  45. if flags.isCellular { networkStatus = .reachable(.cellular) }
  46. self = networkStatus
  47. }
  48. /// Defines the various connection types detected by reachability flags.
  49. public enum ConnectionType {
  50. /// The connection type is either over Ethernet or WiFi.
  51. case ethernetOrWiFi
  52. /// The connection type is a cellular connection.
  53. case cellular
  54. }
  55. }
  56. /// A closure executed when the network reachability status changes. The closure takes a single argument: the
  57. /// network reachability status.
  58. public typealias Listener = (NetworkReachabilityStatus) -> Void
  59. /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`.
  60. public static let `default` = NetworkReachabilityManager()
  61. // MARK: - Properties
  62. /// Whether the network is currently reachable.
  63. open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi }
  64. /// Whether the network is currently reachable over the cellular interface.
  65. ///
  66. /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended.
  67. /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued.
  68. ///
  69. open var isReachableOnCellular: Bool { status == .reachable(.cellular) }
  70. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  71. open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) }
  72. /// `DispatchQueue` on which reachability will update.
  73. public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue")
  74. /// Flags of the current reachability type, if any.
  75. open var flags: SCNetworkReachabilityFlags? {
  76. var flags = SCNetworkReachabilityFlags()
  77. return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil
  78. }
  79. /// The current network reachability status.
  80. open var status: NetworkReachabilityStatus {
  81. flags.map(NetworkReachabilityStatus.init) ?? .unknown
  82. }
  83. /// Mutable state storage.
  84. struct MutableState {
  85. /// A closure executed when the network reachability status changes.
  86. var listener: Listener?
  87. /// `DispatchQueue` on which listeners will be called.
  88. var listenerQueue: DispatchQueue?
  89. /// Previously calculated status.
  90. var previousStatus: NetworkReachabilityStatus?
  91. }
  92. /// `SCNetworkReachability` instance providing notifications.
  93. private let reachability: SCNetworkReachability
  94. /// Protected storage for mutable state.
  95. @Protected
  96. private var mutableState = MutableState()
  97. // MARK: - Initialization
  98. /// Creates an instance with the specified host.
  99. ///
  100. /// - Note: The `host` value must *not* contain a scheme, just the hostname.
  101. ///
  102. /// - Parameters:
  103. /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`).
  104. public convenience init?(host: String) {
  105. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  106. self.init(reachability: reachability)
  107. }
  108. /// Creates an instance that monitors the address 0.0.0.0.
  109. ///
  110. /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
  111. /// status of the device, both IPv4 and IPv6.
  112. public convenience init?() {
  113. var zero = sockaddr()
  114. zero.sa_len = UInt8(MemoryLayout<sockaddr>.size)
  115. zero.sa_family = sa_family_t(AF_INET)
  116. guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil }
  117. self.init(reachability: reachability)
  118. }
  119. private init(reachability: SCNetworkReachability) {
  120. self.reachability = reachability
  121. }
  122. deinit {
  123. stopListening()
  124. }
  125. // MARK: - Listening
  126. /// Starts listening for changes in network reachability status.
  127. ///
  128. /// - Note: Stops and removes any existing listener.
  129. ///
  130. /// - Parameters:
  131. /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default.
  132. /// - listener: `Listener` closure called when reachability changes.
  133. ///
  134. /// - Returns: `true` if listening was started successfully, `false` otherwise.
  135. @discardableResult
  136. open func startListening(onQueue queue: DispatchQueue = .main,
  137. onUpdatePerforming listener: @escaping Listener) -> Bool {
  138. stopListening()
  139. $mutableState.write { state in
  140. state.listenerQueue = queue
  141. state.listener = listener
  142. }
  143. let weakManager = WeakManager(manager: self)
  144. var context = SCNetworkReachabilityContext(
  145. version: 0,
  146. info: Unmanaged.passUnretained(weakManager).toOpaque(),
  147. retain: { info in
  148. let unmanaged = Unmanaged<WeakManager>.fromOpaque(info)
  149. _ = unmanaged.retain()
  150. return UnsafeRawPointer(unmanaged.toOpaque())
  151. },
  152. release: { info in
  153. let unmanaged = Unmanaged<WeakManager>.fromOpaque(info)
  154. unmanaged.release()
  155. },
  156. copyDescription: { info in
  157. let unmanaged = Unmanaged<WeakManager>.fromOpaque(info)
  158. let weakManager = unmanaged.takeUnretainedValue()
  159. let description = weakManager.manager?.flags?.readableDescription ?? "nil"
  160. return Unmanaged.passRetained(description as CFString)
  161. })
  162. let callback: SCNetworkReachabilityCallBack = { _, flags, info in
  163. guard let info = info else { return }
  164. let weakManager = Unmanaged<WeakManager>.fromOpaque(info).takeUnretainedValue()
  165. weakManager.manager?.notifyListener(flags)
  166. }
  167. let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
  168. let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)
  169. // Manually call listener to give initial state, since the framework may not.
  170. if let currentFlags = flags {
  171. reachabilityQueue.async {
  172. self.notifyListener(currentFlags)
  173. }
  174. }
  175. return callbackAdded && queueAdded
  176. }
  177. /// Stops listening for changes in network reachability status.
  178. open func stopListening() {
  179. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  180. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  181. $mutableState.write { state in
  182. state.listener = nil
  183. state.listenerQueue = nil
  184. state.previousStatus = nil
  185. }
  186. }
  187. // MARK: - Internal - Listener Notification
  188. /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed.
  189. ///
  190. /// - Note: Should only be called from the `reachabilityQueue`.
  191. ///
  192. /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status.
  193. func notifyListener(_ flags: SCNetworkReachabilityFlags) {
  194. let newStatus = NetworkReachabilityStatus(flags)
  195. $mutableState.write { state in
  196. guard state.previousStatus != newStatus else { return }
  197. state.previousStatus = newStatus
  198. let listener = state.listener
  199. state.listenerQueue?.async { listener?(newStatus) }
  200. }
  201. }
  202. private final class WeakManager {
  203. weak var manager: NetworkReachabilityManager?
  204. init(manager: NetworkReachabilityManager?) {
  205. self.manager = manager
  206. }
  207. }
  208. }
  209. // MARK: -
  210. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  211. extension SCNetworkReachabilityFlags {
  212. var isReachable: Bool { contains(.reachable) }
  213. var isConnectionRequired: Bool { contains(.connectionRequired) }
  214. var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) }
  215. var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) }
  216. var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) }
  217. var isCellular: Bool {
  218. #if os(iOS) || os(tvOS)
  219. return contains(.isWWAN)
  220. #else
  221. return false
  222. #endif
  223. }
  224. /// Human readable `String` for all states, to help with debugging.
  225. var readableDescription: String {
  226. let W = isCellular ? "W" : "-"
  227. let R = isReachable ? "R" : "-"
  228. let c = isConnectionRequired ? "c" : "-"
  229. let t = contains(.transientConnection) ? "t" : "-"
  230. let i = contains(.interventionRequired) ? "i" : "-"
  231. let C = contains(.connectionOnTraffic) ? "C" : "-"
  232. let D = contains(.connectionOnDemand) ? "D" : "-"
  233. let l = contains(.isLocalAddress) ? "l" : "-"
  234. let d = contains(.isDirect) ? "d" : "-"
  235. let a = contains(.connectionAutomatic) ? "a" : "-"
  236. return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)"
  237. }
  238. }
  239. #endif