swift:如何使用 mongoDB Realm 数据库和身份验证保持 ios 用户登录
问题:swift:如何使用 mongoDB Realm 数据库和身份验证保持 ios 用户登录 我想让用户保持登录状态,并且不需要每次打开应用程序时都显示登录表单。我正在使用 MongoDB Realm 进行数据库和身份验证。现在登录工作正常,但每次打开应用程序时都需要登录。 这是我的登录代码 @objc func signUp() { setLoading(true); app.username
问题:swift:如何使用 mongoDB Realm 数据库和身份验证保持 ios 用户登录
我想让用户保持登录状态,并且不需要每次打开应用程序时都显示登录表单。我正在使用 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)
}
这是我的应用程序 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()
}
}
}
}
如何让用户登录到 MongoDB 领域?
解答
据我了解*,一旦用户进行身份验证,他们将在该设备上保持身份验证“登录”,直到他们手动注销,请记住,一旦他们注销,他们的访问令牌将保持活动 30 分钟。
指南中的两件事
会话的访问令牌在三十分钟后过期。但是,可以通过使用刷新令牌从 MongoDB 领域检索新的访问令牌来启动新会话。 (Important ->) 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")
gTaskApp 是对我们应用程序的全局引用
let gTaskApp = RealmApp(id: Constants.REALM_APP_ID)
*这是一项正在进行的工作,所以请随时纠正我
更多推荐
所有评论(0)