NetworkReachabilityManager.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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))
  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 { return 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 { return status == .reachable(.cellular) }
  70. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  71. open var isReachableOnEthernetOrWiFi: Bool { return 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. return 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. private let mutableState = Protector(MutableState())
  96. // MARK: - Initialization
  97. /// Creates an instance with the specified host.
  98. ///
  99. /// - Note: The `host` value must *not* contain a scheme, just the hostname.
  100. ///
  101. /// - Parameters:
  102. /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`).
  103. public convenience init?(host: String) {
  104. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  105. self.init(reachability: reachability)
  106. }
  107. /// Creates an instance that monitors the address 0.0.0.0.
  108. ///
  109. /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
  110. /// status of the device, both IPv4 and IPv6.
  111. public convenience init?() {
  112. var zero = sockaddr()
  113. zero.sa_len = UInt8(MemoryLayout<sockaddr>.size)
  114. zero.sa_family = sa_family_t(AF_INET)
  115. guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil }
  116. self.init(reachability: reachability)
  117. }
  118. private init(reachability: SCNetworkReachability) {
  119. self.reachability = reachability
  120. }
  121. deinit {
  122. stopListening()
  123. }
  124. // MARK: - Listening
  125. /// Starts listening for changes in network reachability status.
  126. ///
  127. /// - Note: Stops and removes any existing listener.
  128. ///
  129. /// - Parameters:
  130. /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default.
  131. /// - listener: `Listener` closure called when reachability changes.
  132. ///
  133. /// - Returns: `true` if listening was started successfully, `false` otherwise.
  134. @discardableResult
  135. open func startListening(onQueue queue: DispatchQueue = .main,
  136. onUpdatePerforming listener: @escaping Listener) -> Bool {
  137. stopListening()
  138. mutableState.write { state in
  139. state.listenerQueue = queue
  140. state.listener = listener
  141. }
  142. var context = SCNetworkReachabilityContext(version: 0,
  143. info: Unmanaged.passRetained(self).toOpaque(),
  144. retain: nil,
  145. release: nil,
  146. copyDescription: nil)
  147. let callback: SCNetworkReachabilityCallBack = { _, flags, info in
  148. guard let info = info else { return }
  149. let instance = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
  150. instance.notifyListener(flags)
  151. }
  152. let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
  153. let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)
  154. // Manually call listener to give initial state, since the framework may not.
  155. if let currentFlags = flags {
  156. reachabilityQueue.async {
  157. self.notifyListener(currentFlags)
  158. }
  159. }
  160. return callbackAdded && queueAdded
  161. }
  162. /// Stops listening for changes in network reachability status.
  163. open func stopListening() {
  164. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  165. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  166. mutableState.write { state in
  167. state.listener = nil
  168. state.listenerQueue = nil
  169. state.previousStatus = nil
  170. }
  171. }
  172. // MARK: - Internal - Listener Notification
  173. /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed.
  174. ///
  175. /// - Note: Should only be called from the `reachabilityQueue`.
  176. ///
  177. /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status.
  178. func notifyListener(_ flags: SCNetworkReachabilityFlags) {
  179. let newStatus = NetworkReachabilityStatus(flags)
  180. mutableState.write { state in
  181. guard state.previousStatus != newStatus else { return }
  182. state.previousStatus = newStatus
  183. let listener = state.listener
  184. state.listenerQueue?.async { listener?(newStatus) }
  185. }
  186. }
  187. }
  188. // MARK: -
  189. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  190. extension SCNetworkReachabilityFlags {
  191. var isReachable: Bool { return contains(.reachable) }
  192. var isConnectionRequired: Bool { return contains(.connectionRequired) }
  193. var canConnectAutomatically: Bool { return contains(.connectionOnDemand) || contains(.connectionOnTraffic) }
  194. var canConnectWithoutUserInteraction: Bool { return canConnectAutomatically && !contains(.interventionRequired) }
  195. var isActuallyReachable: Bool { return isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) }
  196. var isCellular: Bool {
  197. #if os(iOS) || os(tvOS)
  198. return contains(.isWWAN)
  199. #else
  200. return false
  201. #endif
  202. }
  203. /// Human readable `String` for all states, to help with debugging.
  204. var readableDescription: String {
  205. let W = isCellular ? "W" : "-"
  206. let R = isReachable ? "R" : "-"
  207. let c = isConnectionRequired ? "c" : "-"
  208. let t = contains(.transientConnection) ? "t" : "-"
  209. let i = contains(.interventionRequired) ? "i" : "-"
  210. let C = contains(.connectionOnTraffic) ? "C" : "-"
  211. let D = contains(.connectionOnDemand) ? "D" : "-"
  212. let l = contains(.isLocalAddress) ? "l" : "-"
  213. let d = contains(.isDirect) ? "d" : "-"
  214. let a = contains(.connectionAutomatic) ? "a" : "-"
  215. return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)"
  216. }
  217. }
  218. #endif