2
0

NetworkReachabilityManager.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. public 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. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
  65. /// Whether the network is currently reachable over the WWAN interface.
  66. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
  67. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  68. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
  69. /// The current network reachability status.
  70. public 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. public var listenerQueue: DispatchQueue = DispatchQueue.main
  76. /// A closure executed when the network reachability status changes.
  77. public 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(sizeofValue(address))
  106. address.sin_family = sa_family_t(AF_INET)
  107. guard let reachability = withUnsafePointer(&address, {
  108. SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
  109. }) else { return nil }
  110. self.init(reachability: reachability)
  111. }
  112. private init(reachability: SCNetworkReachability) {
  113. self.reachability = reachability
  114. self.previousFlags = SCNetworkReachabilityFlags()
  115. }
  116. deinit {
  117. stopListening()
  118. }
  119. // MARK: - Listening
  120. /// Starts listening for changes in network reachability status.
  121. ///
  122. /// - returns: `true` if listening was started successfully, `false` otherwise.
  123. @discardableResult
  124. public func startListening() -> Bool {
  125. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  126. context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
  127. let callbackEnabled = SCNetworkReachabilitySetCallback(
  128. reachability,
  129. { (_, flags, info) in
  130. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
  131. reachability.notifyListener(flags)
  132. },
  133. &context
  134. )
  135. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  136. listenerQueue.async {
  137. self.previousFlags = SCNetworkReachabilityFlags()
  138. self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
  139. }
  140. return callbackEnabled && queueEnabled
  141. }
  142. /// Stops listening for changes in network reachability status.
  143. public func stopListening() {
  144. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  145. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  146. }
  147. // MARK: - Internal - Listener Notification
  148. func notifyListener(_ flags: SCNetworkReachabilityFlags) {
  149. guard previousFlags != flags else { return }
  150. previousFlags = flags
  151. listener?(networkReachabilityStatusForFlags(flags))
  152. }
  153. // MARK: - Internal - Network Reachability Status
  154. func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
  155. guard flags.contains(.reachable) else { return .notReachable }
  156. var networkStatus: NetworkReachabilityStatus = .notReachable
  157. if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
  158. if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
  159. if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) }
  160. }
  161. #if os(iOS)
  162. if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
  163. #endif
  164. return networkStatus
  165. }
  166. }
  167. // MARK: -
  168. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  169. /// Returns whether the two network reachability status values are equal.
  170. ///
  171. /// - parameter lhs: The left-hand side value to compare.
  172. /// - parameter rhs: The right-hand side value to compare.
  173. ///
  174. /// - returns: `true` if the two values are equal, `false` otherwise.
  175. public func ==(
  176. lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
  177. rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
  178. -> Bool
  179. {
  180. switch (lhs, rhs) {
  181. case (.unknown, .unknown):
  182. return true
  183. case (.notReachable, .notReachable):
  184. return true
  185. case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
  186. return lhsConnectionType == rhsConnectionType
  187. default:
  188. return false
  189. }
  190. }
  191. #endif