NetworkReachabilityManager.swift 8.6 KB

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