Reachability.swift 15 KB

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