先貼上程式碼,等一下再補上文字敘述XD
今天來嘗試把跟DB相關的行為抽出來寫在database manager
當中。
import Foundation
import FirebaseDatabase
final class DatabaseManager {
static let shared = DatabaseManager() // singleton
//private let database = Database.database().reference()
private let database = Database.database(url: "($DATABASE_URL)").reference()
}
首先我們使用singleton模式,讓db連線一次,之後都使用同一個。
// MARK: - Account Management
extension DatabaseManager {
public func userExists(with email: String,
completion: @escaping ((Bool) -> Void)) {
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "=")
// observe data
database.child(safeEmail).observeSingleEvent(of: .value, with: { snapshot in
guard snapshot.value as? String != nil else {
completion(false)
return
}
completion(true)
})
}
/// Insert new user to database
public func insertUser(with user: ChatAppUser){
database.child(user.safeEmail).setValue([
"first_name": user.firstName,
"last_name": user.lastName
])
}
}
struct ChatAppUser {
let firstName: String
let lastName: String
let emailAddress: String
// let profilePictureUrl: String
var safeEmail: String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "=")
return safeEmail
}
}
把原本的firebase createUser拿掉。
DatabaseManager.shared.userExists(with: email, completion: { [weak self] exists in
guard let strongSelf = self else { // prevent from memory leak
return
}
guard !exists else {
strongSelf.alertUserLoginError(message: "user for that email address already exists")
return
}
FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password, completion: { authResult, error in
guard authResult != nil, error == nil else {
print("error creating user")
return
}
// data entry
DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstname,
lastName: lastname,
emailAddress: email))
// todo: flow check
strongSelf.navigationController?.dismiss(animated: true, completion: nil)
})
})
等一下再來新增文字!