/
NetworkReachabilityMonitor.swift
242 lines (200 loc) · 6.74 KB
/
NetworkReachabilityMonitor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//
// NetworkReachabilityMonitor.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2016-12-05.
//
// © 2016 J. G. Pusey (see LICENSE.md)
//
#if os(iOS) || os(macOS) || os(tvOS)
import Foundation
import SystemConfiguration
///
/// A `NetworkReachabilityMonitor` instance monitors a network node name or
/// address for changes to its reachability.
///
public class NetworkReachabilityMonitor: BaseMonitor {
///
/// Encapsulates changes to the reachability of a network node name or
/// address.
///
public enum Event {
///
/// The reachability status has changed.
///
case statusDidChange(Status)
}
///
/// Encapsulates the reachability of a network node name or address.
///
public enum Status {
///
/// The network node name or address is not reachable.
///
case notReachable
///
/// The network node name or address can be reached via a
/// non-cellular connection.
///
case reachableViaWiFi
#if os(iOS)
///
/// The network node name or address can be reached via a cellular
/// connection.
///
case reachableViaWWAN
#endif
///
/// The reachability of the network node name or address cannot be
/// determined.
///
case unknown
}
///
/// Initializes a new `NetworkReachabilityMonitor` for the network
/// address `0.0.0.0` (meaning “any IPv4 address at all”).
///
/// - Parameters:
/// - queue: The operation queue on which the handler executes.
/// By default, the main operation queue is used.
/// - handler: The handler to call when the reachability of the
/// network node address changes.
///
public init(queue: OperationQueue = .main,
handler: @escaping (Event) -> Void) throws {
self.handler = handler
self.innerQueue = .main
self.networkReachability = NetworkReachabilityInjector.inject()
self.queue = queue
self.unsafePreviousFlags = []
super.init()
var address = sockaddr_in()
address.sin_family = sa_family_t(AF_INET)
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
try withUnsafePointer(to: &address) {
try $0.withMemoryRebound(to: sockaddr.self,
capacity: 1) {
try networkReachability.listen(to: $0)
}
}
}
///
/// Initializes a new `NetworkReachabilityMonitor` for the specified
/// network node name.
///
/// - Parameters:
/// - name: The network node name of the desired host.
/// - queue: The operation queue on which the handler executes.
/// By default, the main operation queue is used.
/// - handler: The handler to call when the reachability of the
/// network node name changes.
///
public init(name: String,
queue: OperationQueue = .main,
handler: @escaping (Event) -> Void) throws {
self.handler = handler
self.innerQueue = .main
self.networkReachability = NetworkReachabilityInjector.inject()
self.queue = queue
self.unsafePreviousFlags = []
super.init()
try networkReachability.listen(to: name)
}
///
/// A Boolean value indicating whether the network node name or address
/// can be reached.
///
public var isReachable: Bool {
#if os(iOS)
return isReachableViaWiFi || isReachableViaWWAN
#else
return isReachableViaWiFi
#endif
}
///
/// A Boolean value indicating whether the network node name or address
/// can be reached via a non-cellular connection.
///
public var isReachableViaWiFi: Bool {
return status == .reachableViaWiFi
}
#if os(iOS)
///
/// A Boolean value indicating whether the network node name or address
/// can be reached via a cellular connection.
///
public var isReachableViaWWAN: Bool {
return status == .reachableViaWWAN
}
#endif
///
/// The reachability of the network node name or address.
///
public var status: Status {
if let flags = currentFlags {
return statusFromFlags(flags)
} else {
return .unknown
}
}
private let handler: (Event) -> Void
private let innerQueue: DispatchQueue
private let networkReachability: NetworkReachabilityProtocol
private let queue: OperationQueue
private var currentFlags: SCNetworkReachabilityFlags? {
var flags: SCNetworkReachabilityFlags = []
return networkReachability.getFlags(&flags) ? flags : nil
}
private var unsafePreviousFlags: SCNetworkReachabilityFlags
private func invokeHandler(_ flags: SCNetworkReachabilityFlags) {
if unsafePreviousFlags != flags {
unsafePreviousFlags = flags
queue.addOperation {
self.handler(.statusDidChange(self.statusFromFlags(flags)))
}
}
}
private func statusFromFlags(_ flags: SCNetworkReachabilityFlags) -> Status {
if !flags.contains(.reachable) {
return .notReachable
}
if flags.contains(.connectionRequired) {
if flags.contains(.interventionRequired) {
return .notReachable
}
if !flags.contains(.connectionOnDemand)
&& !flags.contains(.connectionOnTraffic) {
return .notReachable
}
}
#if os(iOS)
if flags.contains(.isWWAN) {
return .reachableViaWWAN
}
#endif
return .reachableViaWiFi
}
override public func cleanupMonitor() {
networkReachability.setDispatchQueue(nil)
networkReachability.setCallback(nil, nil)
super.cleanupMonitor()
}
override public func configureMonitor() {
super.configureMonitor()
var context = SCNetworkReachabilityContext()
context.info = Unmanaged<NetworkReachabilityMonitor>.passUnretained(self).toOpaque()
let callback: SCNetworkReachabilityCallBack = { _, flags, info in
if let info = info {
let monitor = Unmanaged<NetworkReachabilityMonitor>.fromOpaque(info).takeUnretainedValue()
monitor.invokeHandler(flags)
}
}
networkReachability.setCallback(callback, &context)
networkReachability.setDispatchQueue(innerQueue)
innerQueue.async {
self.unsafePreviousFlags = []
self.invokeHandler(self.currentFlags ?? [])
}
}
}
#endif