我在单例“会话”中有这个注销功能:
class Session: ObservableObject {
static let shared = Session()
private init() {
self.app = App(id: RealmKonstants.getId())
setUser(self.app.currentUser)
}
let app: App
var realm: Realm?
@Published var configuration: Realm.Configuration?
@Published var user_id: ObjectId?
...
func logout() async throws {
try await app.currentUser?.logOut() // realm logout
setUser(nil) // resets a config variable
NavigationManager.shared.authPath = .init() // resets authentication NavigationPath
}
func setUser(_ user: RealmSwift.User? = nil) {
if user != nil {
self.user_id = user?._id
self.configure()
} else {
self.user_id = nil
self.configuration = nil
}
}
}
这就是我如何将用户引导到应用程序的主屏幕(如果他们已登录):
@main
struct MyApp: SwiftUI.App {
@StateObject var manager = Session.shared
...
var body: some Scene {
WindowGroup {
Group {
if let config = manager.configuration { // If this is nil -> go to auth flow
OpenSyncedRealmView()
.environment(\.realmConfiguration, config)
} else {
LandingView()
}
}
}
}
}
从我的设置视图中的按钮调用注销功能时 - 应用程序成功注销:
var body: some View {
VStack {
...
Button {
Task {
try await session.logout()
}
} label: {
Text("signout")
}
...
}
.sheet(isPresented: $logoutSheet) {
Button {
Task {
try await session.logout()
}
} label: {
Text("sure?")
}
}
}
从带有警告的工作表调用函数时 - 应用程序不会注销:
var body: some View {
VStack {
...
Button {
logoutSheet.toggle()
} label: {
Text("signout")
}
...
}
.sheet(isPresented: $logoutSheet) {
Button {
Task {
try await session.logout()
}
} label: {
Text("sure?")
}
}
}
[ 我在应用程序中强制使用 user_id 的地方收到错误(致命错误:在展开可选值时意外发现 nil)。这不是一个好的做法,但奇怪的是,当我从 VStack 中的按钮调用 logout() 时,我没有得到这些致命错误]
我试图将工作表放在 VStack 中的 Button 上。它没有帮助..