Skip to content

Commit c87a850

Browse files
committed
fix(datastore): add networking monitor by regular ping
1 parent 179fa3f commit c87a850

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

AmplifyPlugins/Core/AWSPluginsCore/WebSocket/AmplifyNetworkMonitor.swift

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
// SPDX-License-Identifier: Apache-2.0
66
//
77

8-
8+
import Foundation
99
import Network
1010
import Combine
1111

@@ -19,6 +19,7 @@ public final class AmplifyNetworkMonitor {
1919
}
2020

2121
private let monitor: NWPathMonitor
22+
private var pingMonitor: AnyCancellable?
2223

2324
private let subject = PassthroughSubject<State, Never>()
2425

@@ -38,6 +39,8 @@ public final class AmplifyNetworkMonitor {
3839
label: "com.amazonaws.amplify.ios.network.websocket.monitor",
3940
qos: .userInitiated
4041
))
42+
43+
pingMonitor = startPingMonitor()
4144
}
4245

4346
public func updateState(_ nextState: State) {
@@ -46,6 +49,35 @@ public final class AmplifyNetworkMonitor {
4649

4750
deinit {
4851
subject.send(completion: .finished)
52+
pingMonitor?.cancel()
4953
monitor.cancel()
5054
}
55+
56+
private func pingCloudflare() -> Future<State, Never> {
57+
Future { promise in
58+
let oneDNS = URL(string: "https://1.1.1.1")!
59+
var request = URLRequest(url: oneDNS)
60+
request.httpMethod = "HEAD"
61+
request.timeoutInterval = .seconds(2)
62+
63+
URLSession.shared.dataTask(with: request) { _, response, error in
64+
if let error {
65+
promise(.success(State.offline))
66+
} else if let httpResponse = response as? HTTPURLResponse {
67+
promise(.success(httpResponse.statusCode < 400 ? State.online : State.offline))
68+
}
69+
}.resume()
70+
}
71+
}
72+
73+
private func startPingMonitor() -> AnyCancellable {
74+
return Timer.TimerPublisher(interval: .seconds(2), runLoop: .main, mode: .common)
75+
.autoconnect()
76+
.receive(on: DispatchQueue.global(qos: .default))
77+
.compactMap { [weak self] _ in self?.pingCloudflare() }
78+
.flatMap { $0 }
79+
.sink { [weak self] state in
80+
self?.updateState(state)
81+
}
82+
}
5183
}

0 commit comments

Comments
 (0)