Swift: Firebase Chat App Part 5 - Database Set Up (Real-time) - Xcode 11 - 2022
import Foundation
import FirebaseDatabase
final class DatabaseManager {
static let shared = DatabaseManager()
private let database = Database.database().reference()
private init() {}
}
// Account Management
extension DatabaseManager {
func userExists(with email: String,
completionHandler: @escaping ((Bool) -> Void)) {
database.child(email.convertedPath).observeSingleEvent(of: .value, with: { snapshot in
guard snapshot.value as? String != nil else {
completionHandler(false)
return
}
completionHandler(true)
})
}
/// Inserts new user to database
func insertUser(with user: ChatAppUser) {
database.child(user.emailAddress.convertedPath).setValue([
"first_name" : user.firstName,
"last_name" : user.lastName,
])
}
}
DatabaseManager.shared.userExists(with: email) { exists in
guard !exists else {
// user already exists
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.alertUserLoginError("Id already exists")
}
return
}
}
FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password) { [weak self] result, error in
guard
let self = self,
let _ = result,
error == nil else {
return
}
DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstName, lastName: lastName, emailAddress: email))
self.navigationController?.dismiss(animated: true)
}