iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0

前言

已經快要到三分之二了,標題名稱取到山窮水盡

Firebase Database

Auth

Strong / Weak

LoginViewController.swift

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)
})

Create entry

RegisterViewController.swift

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)
    })
})

Database

DatabaseManager.swift

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,不用造輪的日子真的是非常快樂啊!

參考資源


上一篇
# Day#18 設定、上傳照片與default值
下一篇
Day#20 Dependencies & conversation UI
系列文
來寫看看app好了! Swift探索之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言