swift - 如何让用户保持登录 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。我做错了什么,我该如何解决这个问题?
解决方案
推荐阅读
- mongodb - 使用 mongoose 连接到 mongodb 副本集
- kubernetes - EKS kubectl 日志
突然停止工作 - html - 如何在按钮单击时转到表单/垫子对话框的顶部
- python - 使用 live-progress 和列表理解
- firebase - 需要firebase云函数中的文件并在每个函数中初始化应用程序有什么缺点吗?
- html - 无论如何,我可以在容器内的一行中设置最大数量的 div 吗?
- django - 不为 serializers.ModelSerializer 创建工作方法
- c - C语言中的Pig Latin实现
- php - 为什么有时我需要在 PHP 中用大括号包裹数组变量
- database - Laravel 8 db::rollback 无法处理无 db/fatal 错误或异常