I'm using Realm Mobile Platform with my Realm iOS app, and I'm trying to pop the view controller after a user logs in. This is the code I have now:
let usernameCredentials = SyncCredentials.usernamePassword(username: emailField.text!, password: passwordField.text!, register: false)
let serverURL = URL(string: "http://45.55.220.254:9080")
SyncUser.logIn(with: usernameCredentials, server: serverURL!){ user, error in
if user != nil{
print("signed in")
MyRealm.copyToSyncedRealm()
self.navigationController?.popToRootViewController(animated: true)
}else if let error = error{
self.loginButton.setTitle("Log in", for: .normal)
let alert = UIAlertController(title: "Error", message: String(describing: error), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { void in
}))
self.present(alert, animated: true)
}
}
However, when I log in, the view controller does not pop, and when I click the back button on the navigation item the app freezes. Any idea why this might be happening?
The callback passed to SyncUser.logIn(with:server:)
is invoked on a background queue. Since it's only safe to call into UIKit from the main thread, you'll need to dispatch your work over to the main thread.
SyncUser.logIn(with: usernameCredentials, server: serverURL!) { user, error in
DispatchQueue.main.async {
if user != nil {
// Success…
} else if let error = error {
// Error…
}
}
}