Reachability.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. 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 var notifierRunning = false
  95. fileprivate let reachabilityRef: SCNetworkReachability
  96. fileprivate let reachabilitySerialQueue: DispatchQueue
  97. fileprivate(set) var flags: SCNetworkReachabilityFlags? {
  98. didSet {
  99. guard flags != oldValue else { return }
  100. reachabilityChanged()
  101. }
  102. }
  103. required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  104. self.allowsCellularConnection = true
  105. self.reachabilityRef = reachabilityRef
  106. self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue)
  107. }
  108. public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  109. guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
  110. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
  111. }
  112. public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
  113. var zeroAddress = sockaddr()
  114. zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
  115. zeroAddress.sa_family = sa_family_t(AF_INET)
  116. guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
  117. self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
  118. }
  119. deinit {
  120. stopNotifier()
  121. }
  122. }
  123. public extension Reachability {
  124. // MARK: - *** Notifier methods ***
  125. func startNotifier() throws {
  126. guard !notifierRunning else { return }
  127. let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in
  128. guard let info = info else { return }
  129. let weakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info).takeUnretainedValue()
  130. weakifiedReachability.reachability?.flags = flags
  131. }
  132. let weakifiedReachability = ReachabilityWeakifier(reachability: self)
  133. var context = SCNetworkReachabilityContext(
  134. version: 0,
  135. info: UnsafeMutableRawPointer(Unmanaged<ReachabilityWeakifier>.passUnretained(weakifiedReachability).toOpaque()),
  136. retain: { (info: UnsafeRawPointer) -> UnsafeRawPointer in
  137. return UnsafeRawPointer(Unmanaged<ReachabilityWeakifier>.fromOpaque(info).retain().toOpaque())
  138. },
  139. release: { (info: UnsafeRawPointer) -> Void in
  140. Unmanaged<ReachabilityWeakifier>.fromOpaque(info).release()
  141. },
  142. copyDescription: { (info: UnsafeRawPointer) -> Unmanaged<CFString> in
  143. let weakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info).takeUnretainedValue()
  144. let description = weakifiedReachability.reachability?.description ?? "nil"
  145. return Unmanaged.passRetained(description as CFString)
  146. }
  147. )
  148. if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
  149. stopNotifier()
  150. throw ReachabilityError.UnableToSetCallback
  151. }
  152. if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
  153. stopNotifier()
  154. throw ReachabilityError.UnableToSetDispatchQueue
  155. }
  156. // Perform an initial check
  157. try setReachabilityFlags()
  158. notifierRunning = true
  159. }
  160. func stopNotifier() {
  161. defer { notifierRunning = false }
  162. SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
  163. SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
  164. }
  165. // MARK: - *** Connection test methods ***
  166. @available(*, deprecated, message: "Please use `connection != .none`")
  167. var isReachable: Bool {
  168. return connection != .none
  169. }
  170. @available(*, deprecated, message: "Please use `connection == .cellular`")
  171. var isReachableViaWWAN: Bool {
  172. // Check we're not on the simulator, we're REACHABLE and check we're on WWAN
  173. return connection == .cellular
  174. }
  175. @available(*, deprecated, message: "Please use `connection == .wifi`")
  176. var isReachableViaWiFi: Bool {
  177. return connection == .wifi
  178. }
  179. var description: String {
  180. guard let flags = flags else { return "unavailable flags" }
  181. let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X"
  182. let R = flags.isReachableFlagSet ? "R" : "-"
  183. let c = flags.isConnectionRequiredFlagSet ? "c" : "-"
  184. let t = flags.isTransientConnectionFlagSet ? "t" : "-"
  185. let i = flags.isInterventionRequiredFlagSet ? "i" : "-"
  186. let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-"
  187. let D = flags.isConnectionOnDemandFlagSet ? "D" : "-"
  188. let l = flags.isLocalAddressFlagSet ? "l" : "-"
  189. let d = flags.isDirectFlagSet ? "d" : "-"
  190. return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
  191. }
  192. }
  193. fileprivate extension Reachability {
  194. func setReachabilityFlags() throws {
  195. try reachabilitySerialQueue.sync { [unowned self] in
  196. var flags = SCNetworkReachabilityFlags()
  197. if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) {
  198. self.stopNotifier()
  199. throw ReachabilityError.UnableToGetInitialFlags
  200. }
  201. self.flags = flags
  202. }
  203. }
  204. func reachabilityChanged() {
  205. let block = connection != .none ? whenReachable : whenUnreachable
  206. DispatchQueue.main.async { [weak self] in
  207. guard let self = self else { return }
  208. block?(self)
  209. self.notificationCenter.post(name: .reachabilityChanged, object: self)
  210. }
  211. }
  212. }
  213. extension SCNetworkReachabilityFlags {
  214. typealias Connection = Reachability.Connection
  215. var connection: Connection {
  216. guard isReachableFlagSet else { return .none }
  217. // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
  218. #if targetEnvironment(simulator)
  219. return .wifi
  220. #else
  221. var connection = Connection.none
  222. if !isConnectionRequiredFlagSet {
  223. connection = .wifi
  224. }
  225. if isConnectionOnTrafficOrDemandFlagSet {
  226. if !isInterventionRequiredFlagSet {
  227. connection = .wifi
  228. }
  229. }
  230. if isOnWWANFlagSet {
  231. connection = .cellular
  232. }
  233. return connection
  234. #endif
  235. }
  236. var isOnWWANFlagSet: Bool {
  237. #if os(iOS)
  238. return contains(.isWWAN)
  239. #else
  240. return false
  241. #endif
  242. }
  243. var isReachableFlagSet: Bool {
  244. return contains(.reachable)
  245. }
  246. var isConnectionRequiredFlagSet: Bool {
  247. return contains(.connectionRequired)
  248. }
  249. var isInterventionRequiredFlagSet: Bool {
  250. return contains(.interventionRequired)
  251. }
  252. var isConnectionOnTrafficFlagSet: Bool {
  253. return contains(.connectionOnTraffic)
  254. }
  255. var isConnectionOnDemandFlagSet: Bool {
  256. return contains(.connectionOnDemand)
  257. }
  258. var isConnectionOnTrafficOrDemandFlagSet: Bool {
  259. return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
  260. }
  261. var isTransientConnectionFlagSet: Bool {
  262. return contains(.transientConnection)
  263. }
  264. var isLocalAddressFlagSet: Bool {
  265. return contains(.isLocalAddress)
  266. }
  267. var isDirectFlagSet: Bool {
  268. return contains(.isDirect)
  269. }
  270. var isConnectionRequiredAndTransientFlagSet: Bool {
  271. return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
  272. }
  273. }
  274. /**
  275. The `ReachabilityWeakifier` class wraps the `Reachability` class in a weak
  276. manner in order to break retain cycles when interacting with CoreFoundation
  277. APIs. CoreFoundation-style callbacks expect a pair or retain/release in
  278. addition to the typical info paramter.
  279. If we passed `SCNetworkReachabilitySetCallback` a direct reference to our
  280. `Reachability` class without also providing corresponding retain/release
  281. callbacks, then a race condition can lead to crashes when:
  282. - `Reachability` is deallocated on thread X
  283. - A `SCNetworkReachability` callback(s) is already in flight on thread Y
  284. If we passed `Reachability` directly but also provided retain/release
  285. callbacks as required by CoreFoundation, we would avoid race condition
  286. crashes, but create a retain cycle which would only be broken after calling
  287. `stopNotifier()`.
  288. By both providing retain/release callbacks and wrapping `Reachability` in
  289. a weak wrapper, we:
  290. - fix the race condition crashes by interacting correctly with CoreFoundation
  291. APIs. See "Memory Management Programming Guide for Core Foundation".
  292. - Don't alter the public API of `Reachability.swift`
  293. - Don't introduce any retain cycles thereby still allowing for automatic
  294. stopping of the notifier on `deinit`.
  295. */
  296. private class ReachabilityWeakifier {
  297. weak var reachability: Reachability?
  298. init(reachability: Reachability) {
  299. self.reachability = reachability
  300. }
  301. }