NetworkReachabilityManager.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // NetworkReachabilityManager.swift
  2. //
  3. // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. import SystemConfiguration
  24. /**
  25. The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
  26. WiFi network interfaces.
  27. Reachability can be used to determine background information about why a network operation failed, or to retry
  28. network requests when a connection is established. It should not be used to prevent a user from initiating a network
  29. request, as it's possible that an initial request may be required to establish reachability.
  30. */
  31. public class NetworkReachabilityManager {
  32. /**
  33. Defines the various states of network reachability.
  34. - Unknown: It is unknown whether the network is reachable.
  35. - NotReachable: The network is not reachable.
  36. - ReachableOnWWAN: The network is reachable over the WWAN connection.
  37. - ReachableOnWiFi: The network is reachable over the WiFi connection.
  38. */
  39. public enum NetworkReachabilityStatus {
  40. case Unknown
  41. case NotReachable
  42. case Reachable(ConnectionType)
  43. }
  44. /**
  45. Defines the various connection types detected by reachability flags.
  46. - EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
  47. - WWAN: The connection type is a WWAN connection.
  48. */
  49. public enum ConnectionType {
  50. case EthernetOrWiFi
  51. case WWAN
  52. }
  53. /// A closure executed when the network reachability status changes. The closure takes a single argument: the
  54. /// network reachability status.
  55. public typealias Listener = NetworkReachabilityStatus -> Void
  56. // MARK: - Properties
  57. /// Whether the network is currently reachable.
  58. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
  59. /// Whether the network is currently reachable over the WWAN interface.
  60. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
  61. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  62. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
  63. /// The current network reachability status.
  64. public var networkReachabilityStatus: NetworkReachabilityStatus {
  65. guard let flags = self.flags else { return .Unknown }
  66. return networkReachabilityStatusForFlags(flags)
  67. }
  68. /// The dispatch queue to execute the `listener` closure on.
  69. public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
  70. /// A closure executed when the network reachability status changes.
  71. public var listener: Listener?
  72. private var flags: SCNetworkReachabilityFlags? {
  73. var flags = SCNetworkReachabilityFlags()
  74. if SCNetworkReachabilityGetFlags(reachability, &flags) {
  75. return flags
  76. }
  77. return nil
  78. }
  79. private let reachability: SCNetworkReachability
  80. private var previousFlags: SCNetworkReachabilityFlags
  81. // MARK: - Initialization
  82. /**
  83. Creates a `NetworkReachabilityManager` instance with the specified host.
  84. - parameter host: The host used to evaluate network reachability.
  85. - returns: The new `NetworkReachabilityManager` instance.
  86. */
  87. public convenience init?(host: String) {
  88. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  89. self.init(reachability: reachability)
  90. }
  91. /**
  92. Creates a `NetworkReachabilityManager` instance with the default socket address (`sockaddr_in6`).
  93. - returns: The new `NetworkReachabilityManager` instance.
  94. */
  95. public convenience init?() {
  96. var address = sockaddr_in6()
  97. address.sin6_len = UInt8(sizeofValue(address))
  98. address.sin6_family = sa_family_t(AF_INET6)
  99. guard let reachability = withUnsafePointer(&address, {
  100. SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
  101. }) else { return nil }
  102. self.init(reachability: reachability)
  103. }
  104. private init(reachability: SCNetworkReachability) {
  105. self.reachability = reachability
  106. self.previousFlags = SCNetworkReachabilityFlags()
  107. }
  108. deinit {
  109. stopListening()
  110. }
  111. // MARK: - Listening
  112. /**
  113. Starts listening for changes in network reachability status.
  114. - returns: `true` if listening was started successfully, `false` otherwise.
  115. */
  116. public func startListening() -> Bool {
  117. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  118. context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
  119. let callbackEnabled = SCNetworkReachabilitySetCallback(
  120. reachability,
  121. { (_, flags, info) in
  122. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
  123. reachability.notifyListener(flags)
  124. },
  125. &context
  126. )
  127. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  128. dispatch_async(listenerQueue) {
  129. self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
  130. }
  131. return callbackEnabled && queueEnabled
  132. }
  133. /**
  134. Stops listening for changes in network reachability status.
  135. */
  136. public func stopListening() {
  137. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  138. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  139. }
  140. // MARK: - Internal - Listener Notification
  141. func notifyListener(flags: SCNetworkReachabilityFlags) {
  142. guard previousFlags != flags else { return }
  143. previousFlags = flags
  144. listener?(networkReachabilityStatusForFlags(flags))
  145. }
  146. // MARK: - Internal - Network Reachability Status
  147. func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
  148. guard flags.contains(.Reachable) else { return .NotReachable }
  149. var networkStatus: NetworkReachabilityStatus = .NotReachable
  150. if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
  151. if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
  152. if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
  153. }
  154. #if os(iOS)
  155. if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
  156. #endif
  157. return networkStatus
  158. }
  159. }
  160. // MARK: -
  161. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  162. /**
  163. Returns whether the two network reachability status values are equal.
  164. - parameter lhs: The left-hand side value to compare.
  165. - parameter rhs: The right-hand side value to compare.
  166. - returns: `true` if the two values are equal, `false` otherwise.
  167. */
  168. public func ==(
  169. lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
  170. rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
  171. -> Bool
  172. {
  173. switch (lhs, rhs) {
  174. case (.Unknown, .Unknown):
  175. return true
  176. case (.NotReachable, .NotReachable):
  177. return true
  178. case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
  179. return lhsConnectionType == rhsConnectionType
  180. default:
  181. return false
  182. }
  183. }