NetworkReachabilityManager.swift 7.8 KB

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