Reachability.swift 15 KB

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