NetworkReachabilityManager.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. /// Notification posted when network reachability status changes. The notification `object` contains the update
  25. /// network reachability status as an `NSNumber` which will need to be converted.
  26. public let NetworkReachabilityStatusDidChangeNotification = "com.alamofire.network.reachability.status.did.change"
  27. /**
  28. Defines the various states of network reachability.
  29. - Unknown: It is unknown whether the network is reachable.
  30. - NotReachable: The network is not reachable.
  31. - ReachableOnWWAN: The network is reachable over the WWAN connection.
  32. - ReachableOnWiFi: The network is reachable over the WiFi connection.
  33. */
  34. public enum NetworkReachabilityStatus: Int {
  35. case Unknown = -1
  36. case NotReachable = 0
  37. case ReachableOnWWAN = 1
  38. case ReachableOnWiFi = 2
  39. }
  40. /**
  41. The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
  42. WiFi network interfaces.
  43. Reachability can be used to determine background information about why a network operation failed, or to retry
  44. network requests when a connection is established. It should not be used to prevent a user from initiating a network
  45. request, as it's possible that an initial request may be required to establish reachability.
  46. */
  47. public class NetworkReachabilityManager {
  48. /// A closure executed when the network reachability status changes. The closure takes a single argument: the
  49. /// network reachability status.
  50. public typealias Listener = NetworkReachabilityStatus -> Void
  51. // MARK: - Properties
  52. /// Whether the network is currently reachable.
  53. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnWiFi }
  54. /// Whether the network is currently reachable over the WWAN interface.
  55. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .ReachableOnWWAN }
  56. /// Whether the network is currently reachable over the WiFi interface.
  57. public var isReachableOnWiFi: Bool { return networkReachabilityStatus == .ReachableOnWiFi }
  58. /// The current network reachability status.
  59. public var networkReachabilityStatus: NetworkReachabilityStatus {
  60. guard let flags = self.flags else { return .Unknown }
  61. return networkReachabilityStatusForFlags(flags)
  62. }
  63. /// The dispatch queue to execute the `listener` closure on.
  64. public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue()
  65. /// A closure executed when the network reachability status changes.
  66. public var listener: Listener?
  67. private var flags: SCNetworkReachabilityFlags? {
  68. var flags = SCNetworkReachabilityFlags()
  69. if SCNetworkReachabilityGetFlags(reachability, &flags) {
  70. return flags
  71. }
  72. return nil
  73. }
  74. private let reachability: SCNetworkReachability
  75. private var previousFlags: SCNetworkReachabilityFlags
  76. // MARK: - Initialization
  77. /**
  78. Creates a `NetworkReachabilityManager` instance with the specified host.
  79. - parameter host: The host used to evaluate network reachability.
  80. - returns: The new `NetworkReachabilityManager` instance.
  81. */
  82. public convenience init?(host: String) {
  83. guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
  84. self.init(reachability: reachability)
  85. }
  86. /**
  87. Creates a `NetworkReachabilityManager` instance with the default socket address (`sockaddr_in6`).
  88. - returns: The new `NetworkReachabilityManager` instance.
  89. */
  90. public convenience init?() {
  91. var address = sockaddr_in6()
  92. address.sin6_len = UInt8(sizeofValue(address))
  93. address.sin6_family = sa_family_t(AF_INET6)
  94. guard let reachability = withUnsafePointer(&address, {
  95. SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
  96. }) else { return nil }
  97. self.init(reachability: reachability)
  98. }
  99. private init(reachability: SCNetworkReachability) {
  100. self.reachability = reachability
  101. self.previousFlags = SCNetworkReachabilityFlags()
  102. }
  103. deinit {
  104. stopListening()
  105. }
  106. // MARK: - Listening
  107. /**
  108. Starts listening for changes in network reachability status.
  109. - returns: `true` if listening was started successfully, `false` otherwise.
  110. */
  111. public func startListening() -> Bool {
  112. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  113. context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
  114. let callbackEnabled = SCNetworkReachabilitySetCallback(
  115. reachability,
  116. { (_, flags, info) in
  117. let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
  118. reachability.notifyListener(flags)
  119. },
  120. &context
  121. )
  122. let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
  123. dispatch_async(listenerQueue) {
  124. self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
  125. }
  126. return callbackEnabled && queueEnabled
  127. }
  128. /**
  129. Stops listening for changes in network reachability status.
  130. */
  131. public func stopListening() {
  132. SCNetworkReachabilitySetCallback(reachability, nil, nil)
  133. SCNetworkReachabilitySetDispatchQueue(reachability, nil)
  134. }
  135. // MARK: - Internal - Listener Notification
  136. func notifyListener(flags: SCNetworkReachabilityFlags) {
  137. guard previousFlags != flags else { return }
  138. previousFlags = flags
  139. let networkReachabilityStatus = networkReachabilityStatusForFlags(flags)
  140. listener?(networkReachabilityStatus)
  141. dispatch_async(dispatch_get_main_queue()) {
  142. NSNotificationCenter.defaultCenter().postNotificationName(
  143. NetworkReachabilityStatusDidChangeNotification,
  144. object: networkReachabilityStatus.rawValue
  145. )
  146. }
  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 = .ReachableOnWiFi }
  153. if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) {
  154. if !flags.contains(.InterventionRequired) { networkStatus = .ReachableOnWiFi }
  155. }
  156. #if os(iOS)
  157. if flags.contains(.IsWWAN) { networkStatus = .ReachableOnWWAN }
  158. #endif
  159. return networkStatus
  160. }
  161. }