Read more initial setup and workaround for MongoDB Realm and SwiftUI here.
Authentication
from the left side bar.Authentication Providers
and enable both Allow users to log in anonymously
and Email/Password
. You can also see that there are other various authentication providers available, such as Google and Facebook, for developers to seamlessly integrate.Now that you have enabled Authentication
, let’s create some UI and an actual login page.
Realm-Cocoa
.For instructions on how to do this step, follow the
Set up Swift App
header from this article.
let app = App(id: "ENTER_APP_ID")
func RealmRegister(){
let client = app.emailPasswordAuth
let email = "test@test.com"
let password = "123456"
client.registerUser(email: email, password: password) { (error) in
guard error == nil else {
print("Failed to register: \(error!.localizedDescription)")
e = "Failed to register: \(error!.localizedDescription)"
return
}
print("Successfully registered user.")
}
}
Replace the email and password attribute with your desired email-id and password.
Call the function, and you’ll see the created user within your MongoDB Realm Database users list. However, you will not find the user details within the Confirmed tab; rather, it would available in the Pending tab. That’s because after the account creation, the user has not logged in. Hence, the user would move to the Confirmed user tab only after the login.
Now, let’s create a login function to log our created user in.
func RealmAuth(){
app.login(credentials: Credentials.emailPassword(email: "test@test.com", password: "123456")) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
}
}
}
func RealmAuthAnonymous(){
let anonymousCredentials = Credentials.anonymous
app.login(credentials: anonymousCredentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
}
}
}
Now, you can simply call these functions within any button action to create a seamless login functionality.