2
0

NetworkReachabilityManager.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. //
  2. // NetworkReachabilityManager.swift
  3. //
  4. // Copyright (c) 2014-2016 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)
  25. import Foundation
  26. import SystemConfiguration
  27. /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN 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. /**
  35. Defines the various states of network reachability.
  36. - Unknown: It is unknown whether the network is reachable.
  37. - NotReachable: The network is not reachable.
  38. - ReachableOnWWAN: The network is reachable over the WWAN connection.
  39. - ReachableOnWiFi: The network is reachable over the WiFi connection.
  40. */
  41. /// Defines the various states of network reachability.
  42. ///
  43. /// - unknown: It is unknown whether the network is reachable.
  44. /// - notReachable: The network is not reachable.
  45. /// - reachable: The network is reachable.
  46. public enum NetworkReachabilityStatus {
  47. case unknown
  48. case notReachable
  49. case reachable(ConnectionType)
  50. }
  51. /// Defines the various connection types detected by reachability flags.
  52. ///
  53. /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
  54. /// - wwan: The connection type is a WWAN connection.
  55. public enum ConnectionType {
  56. case ethernetOrWiFi
  57. case wwan
  58. }
  59. /// A closure executed when the network reachability status changes. The closure takes a single argument: the
  60. /// network reachability status.
  61. public typealias Listener = (NetworkReachabilityStatus) -> Void
  62. // MARK: - Properties
  63. /// Whether the network is currently reachable.
  64. open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
  65. /// Whether the network is currently reachable over the WWAN interface.
  66. open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
  67. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  68. open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
  69. /// The current network reachability status.
  70. open var networkReachabilityStatus: NetworkReachabilityStatus {
  71. guard let flags = self.flags else { return .unknown }
  72. return networkReachabilityStatusForFlags(flags)
  73. }
  74. /// The dispatch queue to execute the `listener` closure on.
  75. open var listenerQueue: DispatchQueue = DispatchQueue.main
  76. /// A closure executed when the network reachability status changes.
  77. open var listener: Listener?
  78. private var flags: SCNetworkReachabilityFlags? {
  79. var flags = SCNetworkReachabilityFlags()
  80. if SCNetworkReachabilityGetFlags(reachability, &flags) {
  81. return flags
  82. }
  83. return nil
  84. }
  85. private let reachability: SCNetworkReachability
  86. private var previousFlags: SCNetworkReachabilityFlags
  87. // MARK: - Initialization
  88. /// Creates a `NetworkReachabilityManager` instance with the specified host.
  89. ///
  90. /// - parameter host: The host used to evaluate network reachability.
  91. ///
  92. /// - returns: The new `NetworkReachabilityManager` instance.
  93. public convenience init?(host: String) {
  94. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  95. self.init(reachability: reachability)
  96. }
  97. /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
  98. ///
  99. /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
  100. /// status of the device, both IPv4 and IPv6.
  101. ///
  102. /// - returns: The new `NetworkReachabilityManager` instance.
  103. public convenience init?() {
  104. var address = sockaddr_in()
  105. address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
  106. address.sin_family = sa_family_t(AF_INET)
  107. guard let reachability = withUnsafePointer(to: &address, { pointer in
  108. return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
  109. return SCNetworkReachabilityCreateWithAddress(nil, $0)
  110. }
  111. }) else { return nil }
  112. self.init(reachability: reachability)
  113. }
  114. private init(reachability: SCNetworkReachability) {
  115. self.reachability = reachability
  116. self.previousFlags = SCNetworkReachabilityFlags()
  117. }
  118. deinit {
  119. stopListening()
  120. }
  121. // MARK: - Listening
  122. /// Starts listening for changes in network reachability status.
  123. ///
  124. /// - returns: `true` if listening was started successfully, `false` otherwise.
  125. @discardableResult
  126. open func startListening() -> Bool {
  127. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  128. context.info = Unmanaged.passUnretained(self).toOpaque()
  129. let callbackEnabled = SCNetworkReachabilitySetCallback(
  130. reachability,
  131. { (_, flags, info) in
  132. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
  133. reachability.notifyListener(flags)
  134. },
  135. &context
  136. )
  137. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  138. listenerQueue.async {
  139. self.previousFlags = SCNetworkReachabilityFlags()
  140. self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
  141. }
  142. return callbackEnabled && queueEnabled
  143. }
  144. /// Stops listening for changes in network reachability status.
  145. open func stopListening() {
  146. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  147. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  148. }
  149. // MARK: - Internal - Listener Notification
  150. func notifyListener(_ flags: SCNetworkReachabilityFlags) {
  151. guard previousFlags != flags else { return }
  152. previousFlags = flags
  153. listener?(networkReachabilityStatusForFlags(flags))
  154. }
  155. // MARK: - Internal - Network Reachability Status
  156. func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
  157. guard flags.contains(.reachable) else { return .notReachable }
  158. var networkStatus: NetworkReachabilityStatus = .notReachable
  159. if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
  160. if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
  161. if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
  162. }
  163. #if os(iOS)
  164. if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
  165. #endif
  166. return networkStatus
  167. }
  168. }
  169. // MARK: -
  170. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  171. /// Returns whether the two network reachability status values are equal.
  172. ///
  173. /// - parameter lhs: The left-hand side value to compare.
  174. /// - parameter rhs: The right-hand side value to compare.
  175. ///
  176. /// - returns: `true` if the two values are equal, `false` otherwise.
  177. public func ==(
  178. lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
  179. rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
  180. -> Bool
  181. {
  182. switch (lhs, rhs) {
  183. case (.unknown, .unknown):
  184. return true
  185. case (.notReachable, .notReachable):
  186. return true
  187. case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
  188. return lhsConnectionType == rhsConnectionType
  189. default:
  190. return false
  191. }
  192. }
  193. #endif