(選用) 使用 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 類型對應的類型,如下所示:
NSStringNSNumberNSDictionaryNSArray
舉例來說,您可以使用 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; // ... }];
事件監聽器會收到 FIRDataSnapshot,其中包含事件發生時資料庫中指定位置的資料,並儲存在 value 屬性中。您可以將值指派給適當的原生類型,例如 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) 的值,藉此刪除資料。您可以搭配使用這項技術和 updateChildValues,在單一 API 呼叫中刪除多個子項。
卸載事件監聽器
當您離開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 用戶端會盡可能將該資料與遠端資料庫伺服器和其他用戶端同步。
因此,在任何資料寫入伺服器之前,所有寫入資料庫的作業都會立即觸發本機事件。這表示無論網路延遲或連線狀況如何,應用程式都能持續回應。
恢復連線後,應用程式會收到適當的事件組合,讓用戶端與目前的伺服器狀態保持同步,不必編寫任何自訂程式碼。
如要進一步瞭解離線行為,請參閱「進一步瞭解線上和離線功能」。