FlurSchnaps-iOS/FlurSchnaps/DeviceList.swift
2022-06-07 14:22:17 +02:00

92 lines
2.5 KiB
Swift

import SwiftUI
import PushAPI
import Push
extension String {
var nonEmpty: String? {
isEmpty ? nil : self
}
}
struct DeviceList: View {
let pushToken: PushToken
let authToken: AuthenticationToken
let api: PushClient
@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)
print("Updated device list: \(devices?.count ?? -1)")
DispatchQueue.main.async {
self.devices = devices ?? []
}
}
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),
api: .init(server: URL(string: "https://christophhagen.de/push")!, application: "some"),
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
}
}