-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScannerViewModelExample.swift
96 lines (82 loc) · 2.5 KB
/
ScannerViewModelExample.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
//
// ScannerViewModelExample.swift
// SmartScannerExample
//
// Created by SAM Seamless Network on 12/8/22.
//
import Foundation
import Combine
#if targetEnvironment(simulator)
import SmartScannerSDKSimulator
#else
import SmartScannerSDK
#endif
final class ScannerViewModelExample: ObservableObject {
private let scanner: Scan
private var cancellables = Set<AnyCancellable>()
init() {
self.scanner = SmartScanner.getInstance().getScanInstance()
}
func setupScanner(token: String) {
SmartScanner.getInstance().setup(token: token)
}
func startScan() {
let config = ScanConfig()
scanner.scan(params: config)
.receive(on: RunLoop.main)
.sink { [weak self] completion in
switch completion {
case .finished:
print("Finished!")
case .failure(let error):
/// Treat an `.UNAUTHORIZED` type error
if error == .UNAUTHORIZED {
self?.handle401UnauthorizedErrorAndRescan()
return
}
print(error.description)
}
} receiveValue: { result in
// On success, print the list of deteceted devices
guard
let result,
let devices = result.devices
else {
print("No devices found")
return
}
print("Devices: \(devices)")
}
.store(in: &cancellables)
}
func observeScanProgress() {
scanner
.observeProgress()
.receive(on: RunLoop.main)
.sink { value in
print("Progress: \(value)")
}
.store(in: &cancellables)
}
func observerScanDevices() {
scanner
.observeDevices()
.receive(on: RunLoop.main)
.sink(receiveCompletion: { error in
print("The scanner encountered an error: \(error)")
}, receiveValue: { devices in
print("Detected devices: \(devices)")
})
.store(in: &cancellables)
}
func stopScan() {
scanner.killScan()
}
private func handle401UnauthorizedErrorAndRescan() {
setupScanner(token: refreshToken())
startScan()
}
private func refreshToken() -> String {
// Refresh the token and return a new valid one
}
}