NetworkReachabilityManager.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. #if !os(watchOS)
  23. import Foundation
  24. import SystemConfiguration
  25. /**
  26. The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
  27. WiFi network interfaces.
  28. Reachability can be used to determine background information about why a network operation failed, or to retry
  29. network requests when a connection is established. It should not be used to prevent a user from initiating a network
  30. request, as it's possible that an initial request may be required to establish reachability.
  31. */
  32. public class NetworkReachabilityManager {
  33. /**
  34. Defines the various states of network reachability.
  35. - Unknown: It is unknown whether the network is reachable.
  36. - NotReachable: The network is not reachable.
  37. - ReachableOnWWAN: The network is reachable over the WWAN connection.
  38. - ReachableOnWiFi: The network is reachable over the WiFi connection.
  39. */
  40. public enum NetworkReachabilityStatus {
  41. case Unknown
  42. case NotReachable
  43. case Reachable(ConnectionType)
  44. }
  45. /**
  46. Defines the various connection types detected by reachability flags.
  47. - EthernetOrWiFi: The connection type is either over Ethernet or WiFi.
  48. - WWAN: The connection type is a WWAN connection.
  49. */
  50. public enum ConnectionType {
  51. case EthernetOrWiFi
  52. case WWAN
  53. }
  54. /// A closure executed when the network reachability status changes. The closure takes a single argument: the
  55. /// network reachability status.
  56. public typealias Listener = NetworkReachabilityStatus -> Void
  57. // MARK: - Properties
  58. /// Whether the network is currently reachable.
  59. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
  60. /// Whether the network is currently reachable over the WWAN interface.
  61. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) }
  62. /// Whether the network is currently reachable over Ethernet or WiFi interface.
  63. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) }
  64. /// The current network reachability status.
  65. public var networkReachabilityStatus: NetworkReachabilityStatus {
  66. guard let flags = self.flags else { return .Unknown }
  67. return networkReachabilityStatusForFlags(flags)
  68. }
  69. /// The dispatch queue to execute the `listener` closure on.
  70. public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
  71. /// A closure executed when the network reachability status changes.
  72. public var listener: Listener?
  73. private var flags: SCNetworkReachabilityFlags? {
  74. var flags = SCNetworkReachabilityFlags()
  75. if SCNetworkReachabilityGetFlags(reachability, &flags) {
  76. return flags
  77. }
  78. return nil
  79. }
  80. private let reachability: SCNetworkReachability
  81. private var previousFlags: SCNetworkReachabilityFlags
  82. // MARK: - Initialization
  83. /**
  84. Creates a `NetworkReachabilityManager` instance with the specified host.
  85. - parameter host: The host used to evaluate network reachability.
  86. - returns: The new `NetworkReachabilityManager` instance.
  87. */
  88. public convenience init?(host: String) {
  89. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  90. self.init(reachability: reachability)
  91. }
  92. /**
  93. Creates a `NetworkReachabilityManager` instance with the default socket address (`sockaddr_in6`).
  94. - returns: The new `NetworkReachabilityManager` instance.
  95. */
  96. public convenience init?() {
  97. var address = sockaddr_in6()
  98. address.sin6_len = UInt8(sizeofValue(address))
  99. address.sin6_family = sa_family_t(AF_INET6)
  100. guard let reachability = withUnsafePointer(&address, {
  101. SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
  102. }) else { return nil }
  103. self.init(reachability: reachability)
  104. }
  105. private init(reachability: SCNetworkReachability) {
  106. self.reachability = reachability
  107. self.previousFlags = SCNetworkReachabilityFlags()
  108. }
  109. deinit {
  110. stopListening()
  111. }
  112. // MARK: - Listening
  113. /**
  114. Starts listening for changes in network reachability status.
  115. - returns: `true` if listening was started successfully, `false` otherwise.
  116. */
  117. public func startListening() -> Bool {
  118. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  119. context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
  120. let callbackEnabled = SCNetworkReachabilitySetCallback(
  121. reachability,
  122. { (_, flags, info) in
  123. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
  124. reachability.notifyListener(flags)
  125. },
  126. &context
  127. )
  128. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  129. dispatch_async(listenerQueue) {
  130. self.previousFlags = SCNetworkReachabilityFlags()
  131. self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
  132. }
  133. return callbackEnabled && queueEnabled
  134. }
  135. /**
  136. Stops listening for changes in network reachability status.
  137. */
  138. public 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 flags.contains(.Reachable) else { return .NotReachable }
  151. var networkStatus: NetworkReachabilityStatus = .NotReachable
  152. if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
  153. if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
  154. if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) }
  155. }
  156. #if os(iOS)
  157. if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) }
  158. #endif
  159. return networkStatus
  160. }
  161. }
  162. // MARK: -
  163. extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
  164. /**
  165. Returns whether the two network reachability status values are equal.
  166. - parameter lhs: The left-hand side value to compare.
  167. - parameter rhs: The right-hand side value to compare.
  168. - returns: `true` if the two values are equal, `false` otherwise.
  169. */
  170. public func ==(
  171. lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
  172. rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
  173. -> Bool
  174. {
  175. switch (lhs, rhs) {
  176. case (.Unknown, .Unknown):
  177. return true
  178. case (.NotReachable, .NotReachable):
  179. return true
  180. case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)):
  181. return lhsConnectionType == rhsConnectionType
  182. default:
  183. return false
  184. }
  185. }
  186. #endif