SwiftUI demo
Closed this issue · 2 comments
NSCabezon commented
Hi! I wonder if you could add an example on how to implement it on SwiftUI. I was trying to implement it but since the return of login is a UIKit based viewController I'm not sure if the approach I'm following is correct...
thanks!
Krillle commented
I assume your question refers to how to show the login page in SwiftUI.
You need to create a UIViewControllerRepresentable to inject the UIViewController into a SwiftUI view. Learn more about that technique here: https://medium.com/@max.codes/use-uiviewcontrollers-in-swiftui-views-with-uiviewcontrollerrepresentable-coordinator-5b5f75e45caf
import TeslaSwift
import SwiftUI
struct TeslaWebLogin: UIViewControllerRepresentable {
var api = TeslaSwift()
func makeUIViewController(context: Context) -> TeslaWebLoginViewController {
let (webloginViewController, result) = api.authenticateWeb()
Task { @MainActor in
do {
_ = try await result()
print("Authentication success", api.token?.createdAt as Any, "Authentication status", api.isAuthenticated as Any)
guard api.isAuthenticated else { return }
Task { @MainActor in
do {
let vehicles = try await api.getVehicles()
// > > > post process your vehicles here < < <
} catch {
print("Error",error)
}
}
} catch let error {
print("Error", error)
}
}
return webloginViewController! // FIXME: Optional should be unwrapped, but what to return if nil?
}
func updateUIViewController(_ uiViewController: TeslaWebLoginViewController, context: Context) {
}
}
Now you can call as a SwiftUI View:
import SwiftUI
struct TeslaLogin: View {
var body: some View {
VStack {
TeslaWebLogin()
}
}
}
struct TeslaLogin_Previews: PreviewProvider {
static var previews: some View {
TeslaLogin()
}
}
jonasman commented
Does the current Readme help? if so we can close