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.

238 lines
9.0 KiB

6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
  1. //
  2. // NetworkReachabilityManager.swift
  3. //
  4. // Copyright (c) 2014 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. // Set the previous flags to an unreserved value to represent unknown status
  110. self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30)
  111. }
  112. deinit {
  113. stopListening()
  114. }
  115. // MARK: - Listening
  116. /// Starts listening for changes in network reachability status.
  117. ///
  118. /// - returns: `true` if listening was started successfully, `false` otherwise.
  119. @discardableResult
  120. open func startListening() -> Bool {
  121. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  122. context.info = Unmanaged.passUnretained(self).toOpaque()
  123. let callbackEnabled = SCNetworkReachabilitySetCallback(
  124. reachability,
  125. { (_, flags, info) in
  126. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
  127. reachability.notifyListener(flags)
  128. },
  129. &context
  130. )
  131. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  132. listenerQueue.async {
  133. self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30)
  134. guard let flags = self.flags else { return }
  135. self.notifyListener(flags)
  136. }
  137. return callbackEnabled && queueEnabled
  138. }
  139. /// Stops listening for changes in network reachability status.
  140. open func stopListening() {
  141. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  142. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  143. }
  144. // MARK: - Internal - Listener Notification
  145. func notifyListener(_ flags: SCNetworkReachabilityFlags) {
  146. guard previousFlags != flags else { return }
  147. previousFlags = flags
  148. listener?(networkReachabilityStatusForFlags(flags))
  149. }
  150. // MARK: - Internal - Network Reachability Status
  151. func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
  152. guard isNetworkReachable(with: flags) else { return .notReachable }
  153. var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
  154. #if os(iOS)
  155. if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
  156. #endif
  157. return networkStatus
  158. }
  159. func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
  160. let isReachable = flags.contains(.reachable)
  161. let needsConnection = flags.contains(.connectionRequired)
  162. let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
  163. let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
  164. return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
  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