(選用) 使用 Firebase 本機模擬器套件設計原型並進行測試
在討論應用程式如何讀取即時資料庫及寫入資料之前,我們會先介紹一組工具,讓您用來設計原型及測試即時資料庫功能:Firebase 本機模擬器套件。如果您正在嘗試不同的資料模型、最佳化安全性規則,或想找出最符合成本效益的方式與後端互動,那麼即使不部署即時服務,也能在本機工作。
即時資料庫模擬器屬於本機模擬器套件的一部分,可讓應用程式與模擬資料庫內容和設定互動,並選擇性地與模擬專案資源 (函式、其他資料庫和安全性規則) 互動。
使用即時資料庫模擬器只需完成幾個步驟:
- 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
- 從本機專案目錄的根目錄中執行
firebase emulators:start
。 - 照常透過即時資料庫平台 SDK 或即時資料庫 REST API,從應用程式的原型程式碼發出呼叫。
歡迎查看詳細的即時資料庫和 Cloud Functions 逐步操作說明。建議您也參閱「本機模擬器套件簡介」一文。
取得 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()
和 nil
時,系統會在您讀取其 value
屬性時,為快照傳回 false
。
以下範例將示範社交網誌應用程式,如何從資料庫中擷取貼文的詳細資料:
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
後,系統不會自動移除在子節點上註冊的事件監聽器;您也必須追蹤這些參照,或追蹤這些參照,或控制如何將其移除。
將資料儲存為交易
處理可能會因為並行修改而損毀的資料 (例如漸進式計數器) 時,您可以使用交易作業。您將為這項作業提供兩個引數:更新函式和選用的完成回呼。update 函式會將資料目前狀態當做引數,並傳回您要寫入的新所需狀態。
舉例來說,在社交網誌應用程式範例中,您可以讓使用者為文章加上星號或移除星號,也可以追蹤貼文獲得的星星數量,如下所示:
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 用戶端會「盡可能」將這些資料與遠端資料庫伺服器和其他用戶端同步處理。
因此,在將任何資料寫入伺服器之前,所有寫入資料庫的作業會立即觸發本機事件。換句話說,無論網路延遲或連線狀況,應用程式都會持續回應。
重新建立連線後,應用程式會收到一組適當的事件,讓用戶端與目前的伺服器狀態同步,而不必編寫任何自訂程式碼。
我們會在進一步瞭解線上和離線功能中,進一步說明離線行為。