iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0

前言

先貼上程式碼,等一下再補上文字敘述XD

今天來嘗試把跟DB相關的行為抽出來寫在database manager當中。

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

註冊檢查

RegisterViewController

把原本的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)
    })
})

結語

等一下再來新增文字!


上一篇
Day#15 Firebase Auth
下一篇
Day#17 基本功能=直覺的畫面
系列文
來寫看看app好了! Swift探索之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言