首页 > 解决方案 > 如何让用户保持登录 SwiftUI?

问题描述

我想实现让用户登录 swiftUI。我正在关注 使用 UIStoryboard 实现相同功能的本教程。我能够从 UserDefault 保存和检索数据,但无法让导航查看工作。

@main
struct myApp: App {
  @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

  let persistenceController = PersistenceController.shared
  let settings = UserSettings()
  let state = AppState()
 

var body: some Scene {
    WindowGroup {
        ContentView(state: state)
            .environmentObject(settings)

            .onAppear(perform: {
                print("*******[APP], window group initiated")
            })
      }
    }
  }

这是我的 AppDelegate

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {
    
    print("********[APPDELEGATE], initiated")

        FirebaseApp.configure()
    
    var window: UIWindow?

    window = UIWindow(frame: UIScreen.main.bounds)

        configureInitialRootViewController(for: window)
    
    return true
  }
}

extension AppDelegate {
  func configureInitialRootViewController(for window: UIWindow?) {
      let defaults = UserDefaults.standard
      let settings = UserSettings()
      let state = AppState()

    let persistenceController = PersistenceController.shared
    if let _ = Auth.auth().currentUser,
       let userData = defaults.object(forKey: Constants.UserDefaults.currentUser) as? Data,
       let user = try? JSONDecoder().decode(User.self, from: userData) {
        print("********[APP], @configureInitialRootViewController, user data ", user)
        User.setCurrent(user)

        TabbarView()
            .environment(\.managedObjectContext, persistenceController.container.viewContext)

    } else {
        ContentView(state: state)
            .environmentObject(settings)
    }
     window?.makeKeyAndVisible()
}

}

我能够验证是否在 AppDelegate 中获取了 userDefault 数据,但是如果用户已经登录,我似乎可以让视图导航到 Tabbar。我做错了什么,我该如何解决这个问题?

标签: swiftswiftui

解决方案


推荐阅读