e.i*_*luf 3 realm mongodb swift swiftui
我想让用户保持登录状态,并且每次打开应用程序时都不需要显示登录表单。我正在使用 MongoDB Realm 进行数据库和身份验证。现在登录工作正常,但每次打开应用程序时都需要登录。
这是我的登录代码
@objc func signUp() {
setLoading(true);
app.usernamePasswordProviderClient().registerEmail(username!, password: password!, completion: {[weak self](error) in
// Completion handlers are not necessarily called on the UI thread.
// This call to DispatchQueue.main.sync ensures that any changes to the UI,
// namely disabling the loading indicator and navigating to the next page,
// are handled on the UI thread:
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
print("Signup failed: \(error!)")
self!.errorLabel.text = "Signup failed: \(error!.localizedDescription)"
return
}
print("Signup successful!")
// Registering just registers. Now we need to sign in, but we can reuse the existing username and password.
self!.errorLabel.text = "Signup successful! Signing in..."
self!.signIn()
}
})
}
@objc func signIn() {
print("Log in as user: \(username!)");
setLoading(true);
app.login(withCredential: AppCredentials(username: username!, password: password!)) { [weak self](maybeUser, error) in
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
// Auth error: user already exists? Try logging in as that user.
print("Login failed: \(error!)");
self!.errorLabel.text = "Login failed: \(error!.localizedDescription)"
return
}
guard let user = maybeUser else {
fatalError("Invalid user object?")
}
print("Login succeeded!");
self?.navigationController?.pushViewController(hostingController, animated: true)
}
Run Code Online (Sandbox Code Playgroud)
这是我的应用程序 rootView,我想在其中检查并保持用户登录状态
struct AppRootView: View {
var body: some View {
AnyView {
// check if user has already logged in here and then route them accordingly
if auth.token != nil {
homeMainView()
} else {
LoginController()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用 MongoDB 领域保持用户登录?
据我了解*,一旦用户通过身份验证,他们将在该设备上保持“登录”身份,直到他们被手动注销,请记住,一旦他们注销,他们的访问令牌将保持活动状态 30 分钟。
指南中的两件事
会话的访问令牌在 30 分钟后过期。但是,可以通过使用刷新令牌从 MongoDB Realm 检索新访问令牌来启动新会话。(重要 -> ) SDK 会自动处理刷新访问令牌,因此您在实现客户端应用程序时无需担心这一点。
和
MongoDB Realm 自动处理构成用户会话的访问令牌和刷新令牌。
我们正在做的,似乎工作正常,是这样的:当应用程序打开时,我们调用一个 func handleSignIn,它检查应用程序是否有一个 .currentUser。如果是这样,那么我们配置 Realm。如果不是,则显示登录/注册视图。这是一个片段
func handleSignIn() {
if let _ = gTaskApp.currentUser() {
print("user is logged in")
self.configRealmSync()
} else {
print("not logged in; present sign in/signup view")
Run Code Online (Sandbox Code Playgroud)
gTaskApp 是对我们应用程序的全局引用
let gTaskApp = RealmApp(id: Constants.REALM_APP_ID)
Run Code Online (Sandbox Code Playgroud)
*这是一项正在进行的工作,所以请随时纠正我
| 归档时间: |
|
| 查看次数: |
493 次 |
| 最近记录: |