如何解决如何在异步调用SwfitUI之后加载初始屏幕
在AppDelegate类中,我正在调用Auth API,它返回令牌。然后在UserDefaults中设置令牌。 但是,此时我的HomeView也正在打开,其.onAppear {}函数正在调用另一个api。我想等待Auth API结果的完成。之后要打开HomeView。我该怎么办?
这也是授权或获取令牌的正确方法吗?
这是我的AppDelegate,Service和HomeView:
class AppDelegate: UIResponder,UIApplicationDelegate {
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Service.shared.authorize(userName: "username",password: "password") { (response) in
UserDefaults.standard.set(response.token,forKey: "Token")
}
return true
}
class Service {
func authorize(userName: String,password: String,completion: @escaping(AuthResponse>) -> ()) {
// Here I'm calling auth api
callApiAsync(urlRequest: urlRequest) { (apiResponse) in
completion(apiResponse)
}
}
}
struct HomeView: View {
@ObservedObject var vm = HomeViewModel()
var body: some View {
Text("HomeView")
.onAppear {
self.vm.getList() { response in
}
}
}
}
解决方法
我不知道您在哪里初始化UIWindow
。 AppDelegate / SceneDelegate
我为SceneDelegate
但AppDelegate
制作的样本与此类似。
在请求完成后初始化窗口。
func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
Service.shared.authorize(userName: "username",password: "password") { (response) in
UserDefaults.standard.set(response.token,forKey: "Token")
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: HomeView())
self.window = window
window.makeKeyAndVisible()
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。