This repository was archived by the owner on Oct 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathNetworkMonitor.swift
71 lines (61 loc) · 1.76 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
//
// NetworkMonitor.swift
// RsyncOSX
//
// Created by Thomas Evensen on 20/06/2020.
// Copyright © 2020 Thomas Evensen. All rights reserved.
//
import Foundation
import Network
enum Networkerror: LocalizedError {
case networkdropped
var errorDescription: String? {
switch self {
case .networkdropped:
return NSLocalizedString("Network connection is dropped", comment: "network error") + "..."
}
}
}
final class NetworkMonitor {
var monitor: NWPathMonitor?
var netStatusChangeHandler: (() -> Void)?
/*
var isConnected: Bool {
guard let monitor = monitor else { return false }
return monitor.currentPath.status == .satisfied
}
var interfaceType: NWInterface.InterfaceType? {
guard let monitor = monitor else { return nil }
return monitor.currentPath.availableInterfaces.filter {
monitor.currentPath.usesInterfaceType($0.type)
}.first?.type
}
var availableInterfacesTypes: [NWInterface.InterfaceType]? {
guard let monitor = monitor else { return nil }
return monitor.currentPath.availableInterfaces.map { $0.type }
}
var isExpensive: Bool {
return monitor?.currentPath.isExpensive ?? false
}
*/
init() {
startMonitoring()
}
deinit {
self.stopMonitoring()
}
func startMonitoring() {
monitor = NWPathMonitor()
let queue = DispatchQueue(label: "NetStatus_Monitor")
monitor?.start(queue: queue)
monitor?.pathUpdateHandler = { _ in
self.netStatusChangeHandler?()
}
}
func stopMonitoring() {
if let monitor = monitor {
monitor.cancel()
self.monitor = nil
}
}
}