You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

233 lines
8.8 KiB

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