FlurSchnaps-iOS/FlurSchnaps/DeviceList.swift

92 lines
2.5 KiB
Swift
Raw Normal View History

2022-06-07 11:26:32 +02:00
import SwiftUI
import PushAPI
2022-06-07 14:22:17 +02:00
import Push
2022-06-07 11:26:32 +02:00
extension String {
var nonEmpty: String? {
isEmpty ? nil : self
}
}
struct DeviceList: View {
let pushToken: PushToken
let authToken: AuthenticationToken
2022-06-07 14:22:17 +02:00
let api: PushClient
2022-06-07 11:26:32 +02:00
@Binding
var isPresented: Bool
@State
var devices: [DeviceRegistration]
var body: some View {
NavigationView {
VStack(spacing: 0) {
List(devices) { device in
HStack {
Text(device.name.nonEmpty ?? "Device")
.font(.headline)
Spacer()
VStack(alignment: .leading) {
Text(device.application)
.font(.footnote)
.fontWeight(.bold)
.padding(.bottom, 2)
Text(device.pushToken.prefix(5).hexEncoded + "...")
.font(.caption)
}
}
}.refreshable {
await updateList()
}
}.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: dismiss) {
Text("Cancel")
}
}
}.navigationBarTitle("device-list-title")
}.onAppear() {
Task {
await updateList()
}
}
}
private func updateList() async {
let devices = await api.getDeviceList(pushToken: pushToken, authToken: authToken)
2022-06-07 14:22:17 +02:00
print("Updated device list: \(devices?.count ?? -1)")
2022-06-07 11:26:32 +02:00
DispatchQueue.main.async {
2022-06-07 14:22:17 +02:00
self.devices = devices ?? []
2022-06-07 11:26:32 +02:00
}
}
private func dismiss() {
isPresented = false
}
}
struct DeviceList_Previews: PreviewProvider {
static var previews: some View {
DeviceList(pushToken: Data(repeating: 42, count: 32),
authToken: Data(repeating: 42, count: 16),
2022-06-07 14:22:17 +02:00
api: .init(server: URL(string: "https://christophhagen.de/push")!, application: "some"),
2022-06-07 11:26:32 +02:00
isPresented: .constant(true),
devices: [DeviceRegistration(
pushToken: Data([1,2,3,4,5]),
application: "CC Messenger",
name: "Some")])
}
}
extension DeviceRegistration: Identifiable {
public var id: String {
pushToken.prefix(5).hexEncoded
}
}