iOS使用Firebase Authentication的基本使用

1. 簡介

可以讓用戶使用其電子郵件地址和密碼進行 Firebase 身份驗證,還可以管理應用中的帳號

更多詳細內容可以參考官網:

https://firebase.google.com/docs/auth/ios/password-auth

2. 前置作業

請參考iOS專案如何導入Firebase?

3. 建立帳號

備註:前置作業必須先用好

建立以email的方式創建帳號

啟用並儲存

以下程式碼,可以寫在Button按下去後,執行他

email與password皆是String,就是要建立的帳號

執行後,會呼叫Lambda,error如果是nil代表成功,如果有error則是失敗

//記得import Firebase
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
  
}

Firebase建立帳號有一些規則

Email必須是有效的

密碼必須大於六個字符

呼叫上面function,就會建立帳號,建立好後
就會在Firebase後臺上出現剛剛建立好的帳號

到此建立帳號就完成囉

登入帳號

觸發以下後,會登入帳號,email與password是先前建立好的帳號

//記得import Firebase
Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
    guard let self = self else { return }
                
}

登出帳號

觸發以下後,會登出帳號

//記得import Firebase
let firebaseAuth = Auth.auth()
do {
    try firebaseAuth.signOut()
    navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
    print("Error signing out: %@", signOutError)
}


iOS

iOS專案如何導入Firebase?

1. 簡介 Firebase是Google所開發的一個強大的…

u66f4u591au5167u5bb9…


訂閱Codeilin的旅程,若有最新消息會通知。

廣告

iOS專案如何導入Firebase?

1. 簡介

Firebase是Google所開發的一個強大的Library,裡面有許多實用的功能

包含身分認證、機器學習套件、Cloud Firebase、性能監控等等

更多詳細內容可以參考官網:

https://firebase.google.com/docs

2. Firebase導入iOS專案

首先打開官網:

https://firebase.google.com/

取消打勾,因為牽涉很多其他功能,此文章暫時不需要
從XCode複製Bundle identifier
Apple軟體包ID就是指XCode的Bundle identifier
其他兩個選項可選,此文章不填
將下載的plist用拖移的方式,拖移置對應的專案中
選擇需要使用的Library
選擇iOS專案的語言,將此程式碼複製到專案中的AppDelegate

到此Firebase就成功加入至iOS專案囉


iOS


訂閱Codeilin的旅程,若有最新消息會通知。

廣告

iOS Swift Core Data資料庫使用

1. 在創建專案的時候,將Use Core Data打勾

2. 打勾後專案建立時,會在專案目錄下,出現xxxx.xcdatamodeld,xxxx是專案名字

3. 幫Model建立資料

4. Model處理完後,就能拿來使用

5. 建立一個class架構來使用Core Data

6. 使用方法

1. 在創建專案的時候,將Use Core Data打勾

2. 打勾後專案建立時,會在專案目錄下
出現xxxx.xcdatamodeld,xxxx是專案名字

3. 幫Model建立資料,如下圖
a. Add Entity
b. 修改Entity名字
c. 新增資料和資料形態

4. Model處理完後,就能拿來使用

//記得import才能使用
import CoreData

//取得Context
let context = appDelegate.persistentContainer.viewContext

//forEntityName,就是3.那張圖裡面數字 2 的名字,如下
let coreDataName = "CameraInfoModel"
NSEntityDescription.insertNewObject(
                         forEntityName: coreDataName, 
                         into: context
                     ) as? CameraInfoModel

5. 建立一個class架構來使用Core Data

//1.初始化傳入使用的EntityName,還有NSManagedObjectContext
class CoreDataBase {
    let coreDataName: String?
    let context: NSManagedObjectContext
    init(
    coreDataName: String?,
    context: NSManagedObjectContext
    ) {
        self.coreDataName = coreDataName
        self.context = context
    }
    ...
}
//2.資料讀取,傳入NSPredicate條件篩選
//以及如何排列資料和限制數量
//為了可以彈性所以皆使用?
func fetch(
    predicate: String?,
    sort: [[String: Bool]]?,
    limit:Int?
) -> [CameraInfoModel]? {
    if let coreDataName = self.coreDataName {
        //選擇
        let request = NSFetchRequest<NSFetchRequestResult>(
            entityName: coreDataName
        )
        //條件篩選
        if let predicate = predicate {
            request.predicate = 
                   NSPredicate(format: predicate)
        }
        //資料排列,可以有多個組合
        if let sort = sort {
            var array: [NSSortDescriptor] = []
            for sortCondition in sort {
                for(key, value) in sortCondition {
                array.append(NSSortDescriptor(
                    key: key,
                    ascending: value
                ))
            }
            }
            request.sortDescriptors = array
        }
        //設定長度限制
        if let limitNumber = limit {
            request.fetchLimit = limitNumber
        }
        do {
            //讀取資料
            let results =
            try context.fetch(request) 
                    as? [CameraInfoModel]
                if let results = results {
                    //資料不為nil則回傳
                    return results
                }
            } catch {
                fatalError("\(error)")
            }
        }
    return nil
}
//3. 新增資料
func insert(
    attributes: [[String: String]]
) -> Bool {
    if let coreDataName = self.coreDataName {
        //取得要新增的資料
        let data = NSEntityDescription.insertNewObject(
                forEntityName: coreDataName,
        into: context
        ) as? CameraInfoModel
        //如果有取得到才做
        if let data = data {
            //傳入要設定的資料
            for attribute in attributes {
                for (key, value) in attribute {
                //檢查資料型態
                let type = data
                    .entity
                    .attributesByName[key]?
                    .attributeType
                if type == .integer16AttributeType
                      || type == .integer32AttributeType
                      || type == .integer64AttributeType {
                    //設定資料
                    data.setValue(
                        Int(value), 
                        forKey: key
                    )
                } else if type == .doubleAttributeType
                        || type == .floatAttributeType {
                    //設定資料
                    data.setValue(
                        Double(value), 
                        forKey: key
                    )
                } else if type == .booleanAttributeType {
                    //設定資料
                    data.setValue(
                        value == "true" ?
                            true : false, 
                        forKey: key
                    )
                } else {
                    //設定資料
                    data.setValue(
                        value, 
                        forKey: key
                    )
                }
            }
            }
            do {
                //設定完後將資料儲存
                try context.save()
                    //設定完成返回成功
                    return true
                } catch {
                }
            }
    }
    return false
}
//4. 更新資料
func update(
    predicate: String?,
    attritube: [String: String]
) -> Bool {
    //讀取資料
    if let results = fetch(
            predicate: predicate,
    sort: nil,
    limit: nil
    ) {
        //將讀取的資料做改變
        for result in results {
            for(key, value) in attritube {
            let type = result
                .entity
                .attributesByName[key]?
                .attributeType
            if type == .integer16AttributeType
                    || type == .integer32AttributeType
                    || type == .integer64AttributeType {
                result.setValue(Int(value), forKey: key)
            } else if type == .doubleAttributeType
                    || type == .floatAttributeType {
                result.setValue(Double(value), forKey: key)
            } else if type == .booleanAttributeType {
                result.setValue(
                          value == "true" ? true : false,
                          forKey: key
                )
            } else {
                result.setValue(value, forKey: key)
            }
        }
        }
        do {
            //儲存資料
            try self.context.save()
                //設定完成返回成功
                return true
            } catch {
                fatalError("\(error)")
            }
        }
    return false
}
//5. 刪除資料
func delete(
    predicate: String?
) -> Bool {
    //讀取資料
    if let results = fetch(
            predicate: predicate,
    sort: nil,
    limit: nil
    ) {
        //將讀取的資料刪除
        for result in results {
            context.delete(result)
        }
        do {
            //儲存資料
            try context.save()
                //設定完成返回成功
                return true
            } catch {
            }
        }
    return false
}

6. 使用方法

//取得AppDelegate
let appDelegate = 
          (UIApplication.shared.delegate as? AppDelegate)
if let appDelegate = appDelegate {
    //取得NSManagedObjectContext
    let context = 
        appDelegate.persistentContainer.viewContext
    //初始化CoreDataBase
    let coreDataBase = CoreDataBase(
        coreDataName: "CameraInfoModel", 
        context: context
    )
    //插入資料
    var array: [[String: String]] = [[:]]
    array.append(["name": "John"])
    array.append(["ssid": "DIE12345321"])
    let successed = coreDataBase.insert(attributes: array)
    //讀取資料
    if let results = coreDataBase.fetch(
                        predicate: nil, 
                        sort: [["name": true]], limit: nil
                    ) {
        for result in results {
            print("result \(result.name), \(result.ssid)")
        }
    }
    //更新資料
    let successed = coreDataBase.update(
                        predicate: nil, 
                        attritube: ["ssid": "12345"]
                    )
    //刪除資料
    let successed = coreDataBase.delete(predicate: nil)
    //條件選擇,讀取資料
    if let results = coreDataBase.fetch(
                        predicate: "name = \"John\" || 
                                ssid = \"DIE12345321\"", 
                        sort: [["name": true]], limit: nil
                    ) {
        for result in results {
            print("result \(result.name), \(result.ssid)")
        }
    }
}

訂閱Codeilin的旅程,若有最新消息會通知。

廣告

透過 WordPress.com 建置的網站.

向上 ↑