Reachability.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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, Int32)
  27. case failedToCreateWithHostname(String, Int32)
  28. case unableToSetCallback(Int32)
  29. case unableToSetDispatchQueue(Int32)
  30. case unableToGetFlags(Int32)
  31. }
  32. @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
  33. public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
  34. public extension Notification.Name {
  35. 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 unavailable, wifi, cellular
  53. public var description: String {
  54. switch self {
  55. case .cellular: return "Cellular"
  56. case .wifi: return "WiFi"
  57. case .unavailable: return "No Connection"
  58. }
  59. }
  60. @available(*, deprecated, renamed: "unavailable")
  61. public static let none: Connection = .unavailable
  62. }
  63. public var whenReachable: NetworkReachable?
  64. public var whenUnreachable: NetworkUnreachable?
  65. @available(*, deprecated, renamed: "allowsCellularConnection")
  66. public let reachableOnWWAN: Bool = true
  67. /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
  68. public var allowsCellularConnection: Bool
  69. // The notification center on which "reachability changed" events are being posted
  70. public var notificationCenter: NotificationCenter = NotificationCenter.default
  71. @available(*, deprecated, renamed: "connection.description")
  72. public var currentReachabilityString: String {
  73. return "\(connection)"
  74. }
  75. @available(*, unavailable, renamed: "connection")
  76. public var currentReachabilityStatus: Connection {
  77. return connection
  78. }
  79. public var connection: Connection {
  80. if flags == nil {
  81. try? setReachabilityFlags()
  82. }
  83. switch flags?.connection {
  84. case .unavailable?, nil: return .unavailable
  85. case .cellular?: return allowsCellularConnection ? .cellular : .unavailable
  86. case .wifi?: return .wifi
  87. }
  88. }
  89. fileprivate var isRunningOnDevice: Bool = {
  90. #if targetEnvironment(simulator)
  91. return false
  92. #else
  93. return true
  94. #endif
  95. }()
  96. fileprivate(set) var notifierRunning = false
  97. fileprivate let reachabilityRef: SCNetworkReachability
  98. fileprivate let reachabilitySerialQueue: DispatchQueue
  99. fileprivate let notificationQueue: DispatchQueue?
  100. fileprivate(set) var flags: SCNetworkReachabilityFlags? {
  101. didSet {
  102. guard flags != oldValue else { return }
  103. notifyReachabilityChanged()
  104. }
  105. }
  106. required public init(reachabilityRef: SCNetworkReachability,
  107. queueQoS: DispatchQoS = .default,
  108. targetQueue: DispatchQueue? = nil,
  109. notificationQueue: DispatchQueue? = .main) {
  110. self.allowsCellularConnection = true
  111. self.reachabilityRef = reachabilityRef
  112. self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue)
  113. self.notificationQueue = notificationQueue
  114. }
  115. public convenience init(hostname: String,
  116. queueQoS: DispatchQoS = .default,
  117. targetQueue: DispatchQueue? = nil,
  118. notificationQueue: DispatchQueue? = .main) throws {
  119. guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else {
  120. throw ReachabilityError.failedToCreateWithHostname(hostname, SCError())
  121. }
  122. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue)
  123. }
  124. public convenience init(queueQoS: DispatchQoS = .default,
  125. targetQueue: DispatchQueue? = nil,
  126. notificationQueue: DispatchQueue? = .main) throws {
  127. var zeroAddress = sockaddr()
  128. zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
  129. zeroAddress.sa_family = sa_family_t(AF_INET)
  130. guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else {
  131. throw ReachabilityError.failedToCreateWithAddress(zeroAddress, SCError())
  132. }
  133. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue)
  134. }
  135. deinit {
  136. stopNotifier()
  137. }
  138. }
  139. public extension Reachability {
  140. // MARK: - *** Notifier methods ***
  141. func startNotifier() throws {
  142. guard !notifierRunning else { return }
  143. let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in
  144. guard let info = info else { return }
  145. // `weakifiedReachability` is guaranteed to exist by virtue of our
  146. // retain/release callbacks which we provided to the `SCNetworkReachabilityContext`.
  147. let weakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info).takeUnretainedValue()
  148. // The weak `reachability` _may_ no longer exist if the `Reachability`
  149. // object has since been deallocated but a callback was already in flight.
  150. weakifiedReachability.reachability?.flags = flags
  151. }
  152. let weakifiedReachability = ReachabilityWeakifier(reachability: self)
  153. let opaqueWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.passUnretained(weakifiedReachability).toOpaque()
  154. var context = SCNetworkReachabilityContext(
  155. version: 0,
  156. info: UnsafeMutableRawPointer(opaqueWeakifiedReachability),
  157. retain: { (info: UnsafeRawPointer) -> UnsafeRawPointer in
  158. let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
  159. _ = unmanagedWeakifiedReachability.retain()
  160. return UnsafeRawPointer(unmanagedWeakifiedReachability.toOpaque())
  161. },
  162. release: { (info: UnsafeRawPointer) -> Void in
  163. let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
  164. unmanagedWeakifiedReachability.release()
  165. },
  166. copyDescription: { (info: UnsafeRawPointer) -> Unmanaged<CFString> in
  167. let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info)
  168. let weakifiedReachability = unmanagedWeakifiedReachability.takeUnretainedValue()
  169. let description = weakifiedReachability.reachability?.description ?? "nil"
  170. return Unmanaged.passRetained(description as CFString)
  171. }
  172. )
  173. if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
  174. stopNotifier()
  175. throw ReachabilityError.unableToSetCallback(SCError())
  176. }
  177. if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
  178. stopNotifier()
  179. throw ReachabilityError.unableToSetDispatchQueue(SCError())
  180. }
  181. // Perform an initial check
  182. try setReachabilityFlags()
  183. notifierRunning = true
  184. }
  185. func stopNotifier() {
  186. defer { notifierRunning = false }
  187. SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
  188. SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
  189. }
  190. // MARK: - *** Connection test methods ***
  191. @available(*, deprecated, message: "Please use `connection != .none`")
  192. var isReachable: Bool {
  193. return connection != .unavailable
  194. }
  195. @available(*, deprecated, message: "Please use `connection == .cellular`")
  196. var isReachableViaWWAN: Bool {
  197. // Check we're not on the simulator, we're REACHABLE and check we're on WWAN
  198. return connection == .cellular
  199. }
  200. @available(*, deprecated, message: "Please use `connection == .wifi`")
  201. var isReachableViaWiFi: Bool {
  202. return connection == .wifi
  203. }
  204. var description: String {
  205. return flags?.description ?? "unavailable flags"
  206. }
  207. }
  208. fileprivate extension Reachability {
  209. func setReachabilityFlags() throws {
  210. try reachabilitySerialQueue.sync { [unowned self] in
  211. var flags = SCNetworkReachabilityFlags()
  212. if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) {
  213. self.stopNotifier()
  214. throw ReachabilityError.unableToGetFlags(SCError())
  215. }
  216. self.flags = flags
  217. }
  218. }
  219. func notifyReachabilityChanged() {
  220. let notify = { [weak self] in
  221. guard let self = self else { return }
  222. self.connection != .unavailable ? self.whenReachable?(self) : self.whenUnreachable?(self)
  223. self.notificationCenter.post(name: .reachabilityChanged, object: self)
  224. }
  225. // notify on the configured `notificationQueue`, or the caller's (i.e. `reachabilitySerialQueue`)
  226. notificationQueue?.async(execute: notify) ?? notify()
  227. }
  228. }
  229. extension SCNetworkReachabilityFlags {
  230. typealias Connection = Reachability.Connection
  231. var connection: Connection {
  232. guard isReachableFlagSet else { return .unavailable }
  233. // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
  234. #if targetEnvironment(simulator)
  235. return .wifi
  236. #else
  237. var connection = Connection.unavailable
  238. if !isConnectionRequiredFlagSet {
  239. connection = .wifi
  240. }
  241. if isConnectionOnTrafficOrDemandFlagSet {
  242. if !isInterventionRequiredFlagSet {
  243. connection = .wifi
  244. }
  245. }
  246. if isOnWWANFlagSet {
  247. connection = .cellular
  248. }
  249. return connection
  250. #endif
  251. }
  252. var isOnWWANFlagSet: Bool {
  253. #if os(iOS)
  254. return contains(.isWWAN)
  255. #else
  256. return false
  257. #endif
  258. }
  259. var isReachableFlagSet: Bool {
  260. return contains(.reachable)
  261. }
  262. var isConnectionRequiredFlagSet: Bool {
  263. return contains(.connectionRequired)
  264. }
  265. var isInterventionRequiredFlagSet: Bool {
  266. return contains(.interventionRequired)
  267. }
  268. var isConnectionOnTrafficFlagSet: Bool {
  269. return contains(.connectionOnTraffic)
  270. }
  271. var isConnectionOnDemandFlagSet: Bool {
  272. return contains(.connectionOnDemand)
  273. }
  274. var isConnectionOnTrafficOrDemandFlagSet: Bool {
  275. return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
  276. }
  277. var isTransientConnectionFlagSet: Bool {
  278. return contains(.transientConnection)
  279. }
  280. var isLocalAddressFlagSet: Bool {
  281. return contains(.isLocalAddress)
  282. }
  283. var isDirectFlagSet: Bool {
  284. return contains(.isDirect)
  285. }
  286. var isConnectionRequiredAndTransientFlagSet: Bool {
  287. return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
  288. }
  289. var description: String {
  290. let W = isOnWWANFlagSet ? "W" : "-"
  291. let R = isReachableFlagSet ? "R" : "-"
  292. let c = isConnectionRequiredFlagSet ? "c" : "-"
  293. let t = isTransientConnectionFlagSet ? "t" : "-"
  294. let i = isInterventionRequiredFlagSet ? "i" : "-"
  295. let C = isConnectionOnTrafficFlagSet ? "C" : "-"
  296. let D = isConnectionOnDemandFlagSet ? "D" : "-"
  297. let l = isLocalAddressFlagSet ? "l" : "-"
  298. let d = isDirectFlagSet ? "d" : "-"
  299. return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
  300. }
  301. }
  302. /**
  303. `ReachabilityWeakifier` weakly wraps the `Reachability` class
  304. in order to break retain cycles when interacting with CoreFoundation.
  305. CoreFoundation callbacks expect a pair of retain/release whenever an
  306. opaque `info` parameter is provided. These callbacks exist to guard
  307. against memory management race conditions when invoking the callbacks.
  308. #### Race Condition
  309. If we passed `SCNetworkReachabilitySetCallback` a direct reference to our
  310. `Reachability` class without also providing corresponding retain/release
  311. callbacks, then a race condition can lead to crashes when:
  312. - `Reachability` is deallocated on thread X
  313. - A `SCNetworkReachability` callback(s) is already in flight on thread Y
  314. #### Retain Cycle
  315. If we pass `Reachability` to CoreFoundtion while also providing retain/
  316. release callbacks, we would create a retain cycle once CoreFoundation
  317. retains our `Reachability` class. This fixes the crashes and his how
  318. CoreFoundation expects the API to be used, but doesn't play nicely with
  319. Swift/ARC. This cycle would only be broken after manually calling
  320. `stopNotifier()` — `deinit` would never be called.
  321. #### ReachabilityWeakifier
  322. By providing both retain/release callbacks and wrapping `Reachability` in
  323. a weak wrapper, we:
  324. - interact correctly with CoreFoundation, thereby avoiding a crash.
  325. See "Memory Management Programming Guide for Core Foundation".
  326. - don't alter the public API of `Reachability.swift` in any way
  327. - still allow for automatic stopping of the notifier on `deinit`.
  328. */
  329. private class ReachabilityWeakifier {
  330. weak var reachability: Reachability?
  331. init(reachability: Reachability) {
  332. self.reachability = reachability
  333. }
  334. }