-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathNetworkMonitor.swift
244 lines (214 loc) · 8.91 KB
/
NetworkMonitor.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
243
244
// The monitoring code below is derived from grpc-swift project.
// https://github.com/grpc/grpc-swift
// BEGIN grpc-swift derivation
#if os(iOS)
import CoreTelephony
#endif
import Dispatch
import Foundation
import SystemConfiguration
@objc protocol RadioAccessTechnologyObserverProtocol {
#if os(iOS)
func radioAccessDidChange(_ notification: Notification)
#endif
}
protocol RadioAccessTechnologyNotificationProtocol {
func addObserver(_ observer: RadioAccessTechnologyObserverProtocol)
func removeObserver(_ observer: Any)
}
#if os(iOS)
extension NotificationCenter: RadioAccessTechnologyNotificationProtocol {
func addObserver(_ observer: RadioAccessTechnologyObserverProtocol) {
addObserver(
observer,
selector: #selector(RadioAccessTechnologyObserverProtocol.radioAccessDidChange(_:)),
name: .CTRadioAccessTechnologyDidChange,
object: nil
)
}
}
#else
private struct RadioAccessTechnologyMock: RadioAccessTechnologyNotificationProtocol {
func addObserver(_ observer: RadioAccessTechnologyObserverProtocol) {}
func removeObserver(_ observer: Any) {}
}
#endif
/// This class may be used to monitor changes on the device that can cause gRPC to silently disconnect (making
/// it seem like active calls/connections are hanging), then manually shut down / restart gRPC channels as
/// needed. The root cause of these problems is that the backing gRPC-Core doesn't get the optimizations
/// made by iOS' networking stack when changes occur on the device such as switching from wifi to cellular,
/// switching between 3G and LTE, enabling/disabling airplane mode, etc.
/// Read more: https://github.com/grpc/grpc-swift/tree/master/README.md#known-issues
/// Original issue: https://github.com/grpc/grpc-swift/issues/337
public final class NetworkMonitor: RadioAccessTechnologyObserverProtocol {
public static let queueName = "GRPCClient.NetworkMonitor.queue"
private let queue: DispatchQueue
private let reachability: SCNetworkReachability
#if os(iOS)
private let notification: RadioAccessTechnologyNotificationProtocol
/// Instance of network info being used for obtaining cellular technology names.
public let cellularInfo = CTTelephonyNetworkInfo()
/// Name of the cellular technology being used (e.g., `CTRadioAccessTechnologyLTE`).
public private(set) var cellularName: String?
/// Whether the device is currently using wifi (versus cellular).
public private(set) var isUsingWifi: Bool
#endif
/// Whether the network is currently reachable. Backed by `SCNetworkReachability`.
public private(set) var isReachable: Bool
/// Network state handler.
public var stateHandler: ((State) -> Void)?
/// Represents a state of connectivity.
public struct State: Equatable {
/// The most recent change that was made to the state.
public var lastChange: Change
/// Whether this state is currently reachable/online.
public var isReachable: Bool
public init(change: Change, isReachable: Bool) {
self.lastChange = change
self.isReachable = isReachable
}
}
/// A change in network condition.
public enum Change: Equatable {
/// The device switched from offline to wifi.
case offlineToWifi
/// The device switched from wifi to offline.
case wifiToOffline
#if os(iOS)
/// The device switched from offline to cellular.
case offlineToCellular
/// The device switched from cellular to offline.
case cellularToOffline
/// The device switched from cellular to wifi.
case cellularToWifi
/// The device switched from wifi to cellular.
case wifiToCellular
/// The cellular technology changed (e.g., 3G <> LTE).
case cellularTechnology(technology: String)
#endif
}
#if os(iOS)
public convenience init?(
host: String = "google.com",
queue: DispatchQueue = DispatchQueue(label: NetworkMonitor.queueName),
handler: ((State) -> Void)? = nil
) {
self.init(host: host, queue: queue, notification: NotificationCenter.default, handler: handler)
}
#else
public convenience init?(
host: String = "google.com",
queue: DispatchQueue = DispatchQueue(label: NetworkMonitor.queueName),
handler: ((State) -> Void)? = nil
) {
self.init(host: host, queue: queue, notification: RadioAccessTechnologyMock(), handler: handler)
}
#endif
init?(
host: String,
queue: DispatchQueue,
notification: RadioAccessTechnologyNotificationProtocol,
handler: ((State) -> Void)? = nil
) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else {
return nil
}
var flags = SCNetworkReachabilityFlags()
SCNetworkReachabilityGetFlags(reachability, &flags)
let isReachable = flags.contains(.reachable)
self.isReachable = isReachable
self.queue = queue
self.stateHandler = handler
self.reachability = reachability
#if os(iOS)
self.notification = notification
self.isUsingWifi = !flags.contains(.isWWAN) && isReachable
self.cellularName = cellularInfo.currentRadioAccessTechnology
notification.addObserver(self)
#endif
startMonitoringReachability()
}
deinit {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetMain(),
CFRunLoopMode.commonModes.rawValue)
#if os(iOS)
notification.removeObserver(self)
#endif
}
#if os(iOS)
// MARK: - Cellular
@objc public func radioAccessDidChange(_ notification: Notification) {
queue.async {
let cellularName = notification.object as? String ?? self.cellularInfo.currentRadioAccessTechnology
let notifyForCellular = self.cellularName != cellularName && self.isReachable && !self.isUsingWifi
self.cellularName = cellularName
if notifyForCellular, let cellularName = cellularName {
self.stateHandler?(State(
change: .cellularTechnology(technology: cellularName),
isReachable: self.isReachable
))
}
}
}
#endif
// MARK: - Reachability
private func startMonitoringReachability() {
let info = Unmanaged.passUnretained(self).toOpaque()
var context = SCNetworkReachabilityContext(version: 0, info: info, retain: nil,
release: nil, copyDescription: nil)
let callback: SCNetworkReachabilityCallBack = { _, flags, info in
let observer = info.map { Unmanaged<NetworkMonitor>.fromOpaque($0).takeUnretainedValue() }
observer?.reachabilityDidChange(with: flags)
}
SCNetworkReachabilitySetCallback(reachability, callback, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(),
CFRunLoopMode.commonModes.rawValue)
}
private func reachabilityDidChange(with flags: SCNetworkReachabilityFlags) {
queue.async {
let isReachable = flags.contains(.reachable)
#if os(iOS)
let isUsingWifi = !flags.contains(.isWWAN) && isReachable
#endif
let changeState: Change?
#if os(iOS)
switch (self.isReachable, isReachable, self.isUsingWifi, isUsingWifi) {
case (true, true, true, false):
changeState = .wifiToCellular
case (true, true, false, true):
changeState = .cellularToWifi
case (true, false, true, _):
changeState = .wifiToOffline
case (true, false, false, _):
changeState = .cellularToOffline
case (false, true, _, true):
changeState = .offlineToWifi
case (false, true, _, false):
changeState = .offlineToCellular
case (true, true, true, true),
(true, true, false, false),
(false, false, _, _):
changeState = nil
}
#else
switch (self.isReachable, isReachable) {
case (true, false):
changeState = .wifiToOffline
case (false, true):
changeState = .offlineToWifi
case (false, false),
(true, true):
changeState = nil
}
#endif
#if os(iOS)
self.isUsingWifi = isUsingWifi
#endif
self.isReachable = isReachable
if let changeState = changeState {
self.stateHandler?(State(change: changeState, isReachable: isReachable))
}
}
}
}