Reachability.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. Copyright (c) 2014, Ashley Mills
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice, this
  7. list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  12. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  14. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  15. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  16. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  17. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  18. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  19. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  20. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  21. POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. import SystemConfiguration
  24. import Foundation
  25. public enum ReachabilityError: Error {
  26. case FailedToCreateWithAddress(sockaddr_in)
  27. case FailedToCreateWithHostname(String)
  28. case UnableToSetCallback
  29. case UnableToSetDispatchQueue
  30. case UnableToGetInitialFlags
  31. }
  32. @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
  33. public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
  34. extension Notification.Name {
  35. public static let reachabilityChanged = Notification.Name("reachabilityChanged")
  36. }
  37. public class Reachability {
  38. public typealias NetworkReachable = (Reachability) -> ()
  39. public typealias NetworkUnreachable = (Reachability) -> ()
  40. @available(*, unavailable, renamed: "Connection")
  41. public enum NetworkStatus: CustomStringConvertible {
  42. case notReachable, reachableViaWiFi, reachableViaWWAN
  43. public var description: String {
  44. switch self {
  45. case .reachableViaWWAN: return "Cellular"
  46. case .reachableViaWiFi: return "WiFi"
  47. case .notReachable: return "No Connection"
  48. }
  49. }
  50. }
  51. public enum Connection: CustomStringConvertible {
  52. case none, wifi, cellular
  53. public var description: String {
  54. switch self {
  55. case .cellular: return "Cellular"
  56. case .wifi: return "WiFi"
  57. case .none: return "No Connection"
  58. }
  59. }
  60. }
  61. public var whenReachable: NetworkReachable?
  62. public var whenUnreachable: NetworkUnreachable?
  63. @available(*, deprecated: 4.0, renamed: "allowsCellularConnection")
  64. public let reachableOnWWAN: Bool = true
  65. /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
  66. public var allowsCellularConnection: Bool
  67. // The notification center on which "reachability changed" events are being posted
  68. public var notificationCenter: NotificationCenter = NotificationCenter.default
  69. @available(*, deprecated: 4.0, renamed: "connection.description")
  70. public var currentReachabilityString: String {
  71. return "\(connection)"
  72. }
  73. @available(*, unavailable, renamed: "connection")
  74. public var currentReachabilityStatus: Connection {
  75. return connection
  76. }
  77. public var connection: Connection {
  78. switch flags?.connection {
  79. case .none?, nil: return .none
  80. case .cellular?: return allowsCellularConnection ? .cellular : .none
  81. case .wifi?: return .wifi
  82. }
  83. }
  84. fileprivate var isRunningOnDevice: Bool = {
  85. #if targetEnvironment(simulator)
  86. return false
  87. #else
  88. return true
  89. #endif
  90. }()
  91. fileprivate var notifierRunning = false
  92. fileprivate let reachabilityRef: SCNetworkReachability
  93. fileprivate let reachabilitySerialQueue: DispatchQueue
  94. fileprivate(set) var flags: SCNetworkReachabilityFlags? {
  95. didSet {
  96. guard flags != oldValue else { return }
  97. reachabilityChanged()
  98. }
  99. }
  100. required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  101. self.allowsCellularConnection = true
  102. self.reachabilityRef = reachabilityRef
  103. self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue)
  104. }
  105. public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  106. guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
  107. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
  108. }
  109. public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  110. var zeroAddress = sockaddr()
  111. zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
  112. zeroAddress.sa_family = sa_family_t(AF_INET)
  113. guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
  114. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
  115. }
  116. deinit {
  117. stopNotifier()
  118. }
  119. }
  120. public extension Reachability {
  121. // MARK: - *** Notifier methods ***
  122. func startNotifier() throws {
  123. guard !notifierRunning else { return }
  124. let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in
  125. guard let info = info else { return }
  126. let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
  127. reachability.flags = flags
  128. }
  129. var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
  130. context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
  131. if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
  132. stopNotifier()
  133. throw ReachabilityError.UnableToSetCallback
  134. }
  135. if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
  136. stopNotifier()
  137. throw ReachabilityError.UnableToSetDispatchQueue
  138. }
  139. // Perform an initial check
  140. try reachabilitySerialQueue.sync { [unowned self] in
  141. var flags = SCNetworkReachabilityFlags()
  142. if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) {
  143. self.stopNotifier()
  144. throw ReachabilityError.UnableToGetInitialFlags
  145. }
  146. self.flags = flags
  147. }
  148. notifierRunning = true
  149. }
  150. func stopNotifier() {
  151. defer { notifierRunning = false }
  152. SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
  153. SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
  154. }
  155. // MARK: - *** Connection test methods ***
  156. @available(*, deprecated: 4.0, message: "Please use `connection != .none`")
  157. var isReachable: Bool {
  158. return connection != .none
  159. }
  160. @available(*, deprecated: 4.0, message: "Please use `connection == .cellular`")
  161. var isReachableViaWWAN: Bool {
  162. // Check we're not on the simulator, we're REACHABLE and check we're on WWAN
  163. return connection == .cellular
  164. }
  165. @available(*, deprecated: 4.0, message: "Please use `connection == .wifi`")
  166. var isReachableViaWiFi: Bool {
  167. return connection == .wifi
  168. }
  169. var description: String {
  170. guard let flags = flags else { return "unavailable flags" }
  171. let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X"
  172. let R = flags.isReachableFlagSet ? "R" : "-"
  173. let c = flags.isConnectionRequiredFlagSet ? "c" : "-"
  174. let t = flags.isTransientConnectionFlagSet ? "t" : "-"
  175. let i = flags.isInterventionRequiredFlagSet ? "i" : "-"
  176. let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-"
  177. let D = flags.isConnectionOnDemandFlagSet ? "D" : "-"
  178. let l = flags.isLocalAddressFlagSet ? "l" : "-"
  179. let d = flags.isDirectFlagSet ? "d" : "-"
  180. return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
  181. }
  182. }
  183. fileprivate extension Reachability {
  184. func reachabilityChanged() {
  185. let block = connection != .none ? whenReachable : whenUnreachable
  186. DispatchQueue.main.async { [weak self] in
  187. guard let strongSelf = self else { return }
  188. block?(strongSelf)
  189. strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf)
  190. }
  191. }
  192. }
  193. extension SCNetworkReachabilityFlags {
  194. typealias Connection = Reachability.Connection
  195. var connection: Connection {
  196. guard isReachableFlagSet else { return .none }
  197. // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
  198. #if targetEnvironment(simulator)
  199. return .wifi
  200. #else
  201. var connection = Connection.none
  202. if !isConnectionRequiredFlagSet {
  203. connection = .wifi
  204. }
  205. if isConnectionOnTrafficOrDemandFlagSet {
  206. if !isInterventionRequiredFlagSet {
  207. connection = .wifi
  208. }
  209. }
  210. if isOnWWANFlagSet {
  211. connection = .cellular
  212. }
  213. return connection
  214. #endif
  215. }
  216. var isOnWWANFlagSet: Bool {
  217. #if os(iOS)
  218. return contains(.isWWAN)
  219. #else
  220. return false
  221. #endif
  222. }
  223. var isReachableFlagSet: Bool {
  224. return contains(.reachable)
  225. }
  226. var isConnectionRequiredFlagSet: Bool {
  227. return contains(.connectionRequired)
  228. }
  229. var isInterventionRequiredFlagSet: Bool {
  230. return contains(.interventionRequired)
  231. }
  232. var isConnectionOnTrafficFlagSet: Bool {
  233. return contains(.connectionOnTraffic)
  234. }
  235. var isConnectionOnDemandFlagSet: Bool {
  236. return contains(.connectionOnDemand)
  237. }
  238. var isConnectionOnTrafficOrDemandFlagSet: Bool {
  239. return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
  240. }
  241. var isTransientConnectionFlagSet: Bool {
  242. return contains(.transientConnection)
  243. }
  244. var isLocalAddressFlagSet: Bool {
  245. return contains(.isLocalAddress)
  246. }
  247. var isDirectFlagSet: Bool {
  248. return contains(.isDirect)
  249. }
  250. var isConnectionRequiredAndTransientFlagSet: Bool {
  251. return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
  252. }
  253. }