已經快要到三分之二了,標題名稱取到山窮水盡
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { [weak self] authResult, error in // weak self prevents from retention cycle
guard let strongSelf = self else {
return
}
guard let result = authResult, error == nil else {
print("failed to login with email: \(email)")
return
}
let user = result.user
print("logged in user: \(user)")
strongSelf.navigationController?.dismiss(animated: true, completion: nil)
})
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)
})
})
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()
}
// 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,不用造輪的日子真的是非常快樂啊!