问题描述
在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()
}
}
}