(選用) 使用 Firebase Local Emulator Suite 製作原型並進行測試
在說明應用程式如何從 Realtime Database 讀取及寫入資料之前,請先瞭解可用於原型設計和測試 Realtime Database 功能的一組工具:Firebase Local Emulator Suite。如果您正在嘗試不同的資料模型、調整安全性規則,或是尋找與後端互動時最經濟實惠的方式,那麼在本地作業而不部署即時服務,就是絕佳的選擇。
Realtime Database模擬器是 Local Emulator Suite 的一部分,可讓應用程式與模擬的資料庫內容和設定互動,以及選擇性地與模擬的專案資源 (函式、其他資料庫和安全性規則) 互動。
使用 Realtime Database 模擬器只需幾個步驟:
- 在應用程式的測試設定中加入一行程式碼,即可連線至模擬器。
- 從本機專案目錄的根目錄執行
firebase emulators:start
。 - 使用 Realtime Database 平台 SDK 照常從應用程式的原型程式碼發出呼叫,或使用 Realtime Database REST API。
我們提供詳細的逐步操作說明,其中包含 Realtime Database 和 Cloud Functions。建議您也參閱 Local Emulator Suite 簡介。
取得 FIRDatabaseReference
如要從資料庫讀取或寫入資料,您需要 FIRDatabaseReference
的執行個體:
Swift
var ref: DatabaseReference! ref = Database.database().reference()
Objective-C
@property (strong, nonatomic) FIRDatabaseReference *ref; self.ref = [[FIRDatabase database] reference];
寫入資料
本文將介紹讀取及寫入 Firebase 資料的基本概念。
Firebase 資料會寫入 Database
參照,並透過將非同步事件監聽器附加至該參照來擷取。監聽器會針對資料的初始狀態觸發一次,並且在資料變更時會再次觸發。
基本寫入作業
如要執行基本寫入作業,可以使用 setValue
將資料儲存至指定參照,並取代該路徑中的所有現有資料。您可以使用這個方法執行下列操作:
- 請按照下列方式,將對應的可用 JSON 類型傳遞給型別:
NSString
NSNumber
NSDictionary
NSArray
舉例來說,您可以按照下列方式新增使用者:setValue
Swift
self.ref.child("users").child(user.uid).setValue(["username": username])
Objective-C
[[[self.ref child:@"users"] child:authResult.user.uid] setValue:@{@"username": username}];
以這種方式使用 setValue
會覆寫指定位置的資料,包括所有子節點。不過,您還是可以更新子項,不必重新編寫整個物件。如要允許使用者更新個人資料,可以按照下列方式更新使用者名稱:
Swift
self.ref.child("users/\(user.uid)/username").setValue(username)
Objective-C
[[[[_ref child:@"users"] child:user.uid] child:@"username"] setValue:username];
讀取資料
監聽值事件,讀取資料
如要在路徑讀取資料並監聽變更,請使用 FIRDatabaseReference
的 observeEventType:withBlock
觀察 FIRDataEventTypeValue
事件。
事件類型 | 常見用途 |
---|---|
FIRDataEventTypeValue |
讀取及監聽對路徑完整內容的變更。 |
您可以使用 FIRDataEventTypeValue
事件讀取指定路徑的資料,因為該資料在事件發生時存在。附加監聽器時,系統會觸發這個方法一次,之後每當資料 (包括任何子項) 變更時,系統也會觸發這個方法。事件回呼會傳遞 snapshot
,其中包含該位置的所有資料,包括子項資料。如果沒有資料,當您呼叫 exists()
時,快照會傳回 false
,而當您讀取其 value
屬性時,快照會傳回 nil
。
以下範例說明社交網誌應用程式如何從資料庫擷取貼文詳細資料:
Swift
refHandle = postRef.observe(DataEventType.value, with: { snapshot in // ... })
Objective-C
_refHandle = [_postRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) { NSDictionary *postDict = snapshot.value; // ... }];
監聽器會在 value
屬性中收到 FIRDataSnapshot
,其中包含事件發生時資料庫中指定位置的資料。您可以將值指派給適當的原生型別,例如 NSDictionary
。
如果該位置沒有資料,則 value
為 nil
。
讀取資料一次
使用 getData() 讀取一次
無論應用程式處於連線或離線狀態,SDK 都能管理與資料庫伺服器的互動。
一般而言,您應使用上述值事件技術讀取資料,以便在後端資料更新時收到通知。這些技術可減少用量和帳單費用,並經過最佳化,能為使用者提供最佳的線上和離線體驗。
如果只需要資料一次,可以使用 getData()
從資料庫取得資料快照。如果 getData()
無法傳回伺服器值,用戶端會探查本機儲存空間快取,如果仍找不到該值,就會傳回錯誤。
以下範例說明如何從資料庫擷取使用者的公開使用者名稱:
Swift
do { let snapshot = try await ref.child("users/\(uid)/username").getData() let userName = snapshot.value as? String ?? "Unknown" } catch { print(error) }
Objective-C
NSString *userPath = [NSString stringWithFormat:@"users/%@/username", uid]; [[ref child:userPath] getDataWithCompletionBlock:^(NSError * _Nullable error, FIRDataSnapshot * _Nonnull snapshot) { if (error) { NSLog(@"Received an error %@", error); return; } NSString *userName = snapshot.value; }];
不必要地使用 getData()
會增加頻寬用量,導致效能降低。如要避免這種情況,請使用上述即時監聽器。
使用觀察器讀取一次資料
在某些情況下,您可能希望系統立即傳回本機快取中的值,而不是檢查伺服器上是否有更新的值。在這些情況下,您可以立即使用 observeSingleEventOfType
從本機磁碟快取取得資料。
這類資料只需要載入一次,且預期不會經常變更或需要主動監聽,因此非常實用。舉例來說,在先前的範例中,網誌應用程式會在使用者開始撰寫新文章時,使用這個方法載入使用者設定檔:
Swift
let userID = Auth.auth().currentUser?.uid ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { snapshot in // Get user value let value = snapshot.value as? NSDictionary let username = value?["username"] as? String ?? "" let user = User(username: username) // ... }) { error in print(error.localizedDescription) }
Objective-C
NSString *userID = [FIRAuth auth].currentUser.uid; [[[_ref child:@"users"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) { // Get user value User *user = [[User alloc] initWithUsername:snapshot.value[@"username"]]; // ... } withCancelBlock:^(NSError * _Nonnull error) { NSLog(@"%@", error.localizedDescription); }];
更新或刪除資料
更新特定欄位
如要同時寫入節點的特定子項,而不覆寫其他子節點,請使用 updateChildValues
方法。
呼叫 updateChildValues
時,您可以指定鍵的路徑,更新較低層級的子項值。如果資料儲存在多個位置,以便更妥善地擴充,您可以使用資料扇出更新所有資料執行個體。舉例來說,社群部落格應用程式可能想建立貼文,並同時更新至最近的活動動態消息和發布貼文的使用者活動動態消息。為此,網誌應用程式會使用類似下列的程式碼:
Swift
guard let key = ref.child("posts").childByAutoId().key else { return } let post = ["uid": userID, "author": username, "title": title, "body": body] let childUpdates = ["/posts/\(key)": post, "/user-posts/\(userID)/\(key)/": post] ref.updateChildValues(childUpdates)
Objective-C
NSString *key = [[_ref child:@"posts"] childByAutoId].key; NSDictionary *post = @{@"uid": userID, @"author": username, @"title": title, @"body": body}; NSDictionary *childUpdates = @{[@"/posts/" stringByAppendingString:key]: post, [NSString stringWithFormat:@"/user-posts/%@/%@/", userID, key]: post}; [_ref updateChildValues:childUpdates];
這個範例會使用 childByAutoId
在節點中建立貼文,其中包含 /posts/$postid
中所有使用者的貼文,並同時使用 getKey()
擷取金鑰。然後,您可以使用這個鍵在 /user-posts/$userid/$postid
的使用者貼文中建立第二個項目。
使用這些路徑,您只需呼叫一次 updateChildValues
,即可同時更新 JSON 樹狀結構中的多個位置,例如這個範例會在兩個位置建立新貼文。以這種方式進行的同步更新是不可分割的作業:所有更新都會成功,或所有更新都會失敗。
新增完成區塊
如要瞭解資料的提交時間,可以新增完成區塊。setValue
和 updateChildValues
都會採用選用的完成區塊,在寫入作業已提交至資料庫時呼叫。這個接聽程式有助於追蹤已儲存的資料,以及仍在同步的資料。如果呼叫失敗,系統會將錯誤物件傳遞至接聽程式,指出失敗原因。
Swift
do { try await ref.child("users").child(user.uid).setValue(["username": username]) print("Data saved successfully!") } catch { print("Data could not be saved: \(error).") }
Objective-C
[[[_ref child:@"users"] child:user.uid] setValue:@{@"username": username} withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) { if (error) { NSLog(@"Data could not be saved: %@", error); } else { NSLog(@"Data saved successfully."); } }];
刪除資料
如要刪除資料,最簡單的方法是在該資料位置的參照上呼叫 removeValue
。
您也可以指定 nil
做為其他寫入作業的值 (例如 setValue
或 updateChildValues
),藉此刪除資料。您可以使用這項技術,透過單一 API 呼叫刪除多個子項。updateChildValues
卸離監聽器
離開 ViewController
後,觀察員不會自動停止同步資料。如果未正確移除觀察器,系統會繼續將資料同步到本機記憶體。不再需要觀察器時,請將相關聯的 FIRDatabaseHandle
傳遞至 removeObserverWithHandle
方法,即可移除觀察器。
將回呼區塊新增至參照時,系統會傳回 FIRDatabaseHandle
。這些控制代碼可用來移除回呼區塊。
如果已將多個監聽器新增至資料庫參照,系統會在引發事件時呼叫每個監聽器。如要停止同步處理該位置的資料,您必須呼叫 removeAllObservers
方法,移除該位置的所有觀察者。
在監聽器上呼叫 removeObserverWithHandle
或 removeAllObservers
不會自動移除在子節點上註冊的監聽器,您也必須追蹤這些參照或控制代碼,才能移除監聽器。
將資料儲存為交易
處理可能因並行修改而損毀的資料 (例如遞增計數器) 時,可以使用交易作業。這項作業會提供兩個引數:更新函式和選用的完成回呼。更新函式會將資料的目前狀態做為引數,並傳回您要寫入的新所需狀態。
舉例來說,在社群網誌應用程式範例中,您可以允許使用者為貼文加上和移除星號,並追蹤貼文獲得的星號數量,如下所示:
Swift
ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in if var post = currentData.value as? [String: AnyObject], let uid = Auth.auth().currentUser?.uid { var stars: [String: Bool] stars = post["stars"] as? [String: Bool] ?? [:] var starCount = post["starCount"] as? Int ?? 0 if let _ = stars[uid] { // Unstar the post and remove self from stars starCount -= 1 stars.removeValue(forKey: uid) } else { // Star the post and add self to stars starCount += 1 stars[uid] = true } post["starCount"] = starCount as AnyObject? post["stars"] = stars as AnyObject? // Set value and report transaction success currentData.value = post return TransactionResult.success(withValue: currentData) } return TransactionResult.success(withValue: currentData) }) { error, committed, snapshot in if let error = error { print(error.localizedDescription) } }
Objective-C
[ref runTransactionBlock:^FIRTransactionResult * _Nonnull(FIRMutableData * _Nonnull currentData) { NSMutableDictionary *post = currentData.value; if (!post || [post isEqual:[NSNull null]]) { return [FIRTransactionResult successWithValue:currentData]; } NSMutableDictionary *stars = post[@"stars"]; if (!stars) { stars = [[NSMutableDictionary alloc] initWithCapacity:1]; } NSString *uid = [FIRAuth auth].currentUser.uid; int starCount = [post[@"starCount"] intValue]; if (stars[uid]) { // Unstar the post and remove self from stars starCount--; [stars removeObjectForKey:uid]; } else { // Star the post and add self to stars starCount++; stars[uid] = @YES; } post[@"stars"] = stars; post[@"starCount"] = @(starCount); // Set value and report transaction success currentData.value = post; return [FIRTransactionResult successWithValue:currentData]; } andCompletionBlock:^(NSError * _Nullable error, BOOL committed, FIRDataSnapshot * _Nullable snapshot) { // Transaction completed if (error) { NSLog(@"%@", error.localizedDescription); } }];
如果多位使用者同時為同一則貼文加上星號,或用戶端資料過時,使用交易可避免星號計數錯誤。FIRMutableData
類別中包含的值最初是路徑的用戶端最後已知值,如果沒有,則為 nil
。伺服器會比較初始值與目前值,如果兩者相符,就會接受交易,否則會拒絕。如果交易遭拒,伺服器會將目前值傳回給用戶端,用戶端會使用更新後的值再次執行交易。這個程序會重複執行,直到交易獲得接受或嘗試次數過多為止。
不可分割的伺服器端遞增
在上述用途中,我們會將兩個值寫入資料庫:為貼文加上/取消加星號的使用者 ID,以及遞增的星號數。如果我們已知道使用者正在為貼文加上星號,則可使用原子遞增作業,而非交易。
Swift
let updates = [ "posts/\(postID)/stars/\(userID)": true, "posts/\(postID)/starCount": ServerValue.increment(1), "user-posts/\(postID)/stars/\(userID)": true, "user-posts/\(postID)/starCount": ServerValue.increment(1) ] as [String : Any] Database.database().reference().updateChildValues(updates)
Objective-C
NSDictionary *updates = @{[NSString stringWithFormat: @"posts/%@/stars/%@", postID, userID]: @TRUE, [NSString stringWithFormat: @"posts/%@/starCount", postID]: [FIRServerValue increment:@1], [NSString stringWithFormat: @"user-posts/%@/stars/%@", postID, userID]: @TRUE, [NSString stringWithFormat: @"user-posts/%@/starCount", postID]: [FIRServerValue increment:@1]}; [[[FIRDatabase database] reference] updateChildValues:updates];
這段程式碼不會使用交易作業,因此如果發生更新衝突,系統不會自動重新執行。不過,由於遞增作業是直接在資料庫伺服器上進行,因此不會發生衝突。
如要偵測及拒絕應用程式專屬的衝突,例如使用者為先前已加星號的貼文加上星號,請為該用途編寫自訂安全規則。
離線處理資料
如果用戶端失去網路連線,應用程式仍會正常運作。
連線至 Firebase 資料庫的每個用戶端都會維護任何有效資料的內部版本。寫入資料時,系統會先寫入這個本機版本。Firebase 用戶端隨後會盡力將資料與遠端資料庫伺服器和其他用戶端同步。
因此,所有寫入資料庫的作業都會立即觸發本機事件,然後才將資料寫入伺服器。也就是說,無論網路延遲或連線狀況如何,應用程式都能保持回應。
重新建立連線後,應用程式會收到適當的事件集,讓用戶端與目前的伺服器狀態同步,不必撰寫任何自訂程式碼。
如要進一步瞭解離線行為,請參閱「進一步瞭解線上和離線功能」。