即使您的應用暫時失去網絡連接,Firebase 應用程序也能正常運行。此外,Firebase 還提供了用於在本地保存數據、管理狀態和處理延遲的工具。
磁盤持久化
Firebase 應用程序會自動處理臨時網絡中斷。緩存數據在離線狀態下可用,並且當網絡連接恢復時,Firebase 會重新發送所有寫入。
當您啟用磁盤持久性時,您的應用程序會將數據本地寫入設備,以便您的應用程序可以在離線狀態下保持狀態,即使用戶或操作系統重新啟動應用程序也是如此。
您只需一行代碼即可啟用磁盤持久性。
迅速
Database.database().isPersistenceEnabled = true
Objective-C
[FIRDatabase database].persistenceEnabled = YES;
持久行為
通過啟用持久性,Firebase 實時數據庫客戶端在聯機時同步的任何數據都會持久保存到磁盤,並且即使在用戶或操作系統重新啟動應用程序時也可以脫機使用。這意味著您的應用程序可以像在線一樣使用存儲在緩存中的本地數據。偵聽器回調將繼續觸發本地更新。
Firebase 實時數據庫客戶端會自動保留應用離線時執行的所有寫入操作的隊列。啟用持久性後,此隊列也會持久保存到磁盤,因此當用戶或操作系統重新啟動應用程序時,所有寫入都可用。當應用重新獲得連接時,所有操作都會發送到 Firebase 實時數據庫服務器。
如果您的應用使用Firebase 身份驗證,Firebase 實時數據庫客戶端會在應用重新啟動時保留用戶的身份驗證令牌。如果您的應用程序離線時身份驗證令牌過期,客戶端將暫停寫入操作,直到您的應用程序重新對用戶進行身份驗證,否則寫入操作可能會因安全規則而失敗。
保持數據新鮮
Firebase 實時數據庫為活動偵聽器同步並存儲數據的本地副本。此外,您可以保持特定位置同步。
迅速
let scoresRef = Database.database().reference(withPath: "scores") scoresRef.keepSynced(true)
Objective-C
FIRDatabaseReference *scoresRef = [[FIRDatabase database] referenceWithPath:@"scores"]; [scoresRef keepSynced:YES];
即使引用沒有活動偵聽器,Firebase 實時數據庫客戶端也會自動下載這些位置的數據並使其保持同步。您可以使用以下代碼行重新關閉同步。
迅速
scoresRef.keepSynced(false)
Objective-C
[scoresRef keepSynced:NO];
默認情況下,會緩存 10MB 的先前同步數據。這對於大多數應用來說應該足夠了。如果緩存超出其配置的大小,Firebase 實時數據庫將清除最近最少使用的數據。保持同步的數據不會從緩存中清除。
離線查詢數據
Firebase 實時數據庫存儲從查詢返回的數據,以便在離線時使用。對於離線時構建的查詢,Firebase 實時數據庫將繼續處理之前加載的數據。如果請求的數據尚未加載,Firebase 實時數據庫將從本地緩存加載數據。當網絡連接再次可用時,數據將加載並反映查詢。
例如,此代碼查詢 Firebase 分數實時數據庫中的最後四項
迅速
let scoresRef = Database.database().reference(withPath: "scores") scoresRef.queryOrderedByValue().queryLimited(toLast: 4).observe(.childAdded) { snapshot in print("The \(snapshot.key) dinosaur's score is \(snapshot.value ?? "null")") }
Objective-C
FIRDatabaseReference *scoresRef = [[FIRDatabase database] referenceWithPath:@"scores"]; [[[scoresRef queryOrderedByValue] queryLimitedToLast:4] observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) { NSLog(@"The %@ dinosaur's score is %@", snapshot.key, snapshot.value); }];
假設用戶失去連接、離線並重新啟動應用程序。當仍處於離線狀態時,應用程序會從同一位置查詢最後兩項。此查詢將成功返回最後兩項,因為應用程序已加載上述查詢中的所有四個項目。
迅速
scoresRef.queryOrderedByValue().queryLimited(toLast: 2).observe(.childAdded) { snapshot in print("The \(snapshot.key) dinosaur's score is \(snapshot.value ?? "null")") }
Objective-C
[[[scoresRef queryOrderedByValue] queryLimitedToLast:2] observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) { NSLog(@"The %@ dinosaur's score is %@", snapshot.key, snapshot.value); }];
在前面的示例中,Firebase 實時數據庫客戶端通過使用持久緩存為得分最高的兩隻恐龍引發“添加子項”事件。但它不會引發“值”事件,因為應用程序從未在在線時執行過該查詢。
如果應用程序在離線時請求最後六個項目,它將立即獲得四個緩存項目的“子添加”事件。當設備重新上線時,Firebase 實時數據庫客戶端與服務器同步並獲取應用程序的最後兩個“添加子項”和“值”事件。
離線處理交易
應用程序離線時執行的任何事務都會排隊。一旦應用程序重新獲得網絡連接,事務就會發送到實時數據庫服務器。
管理存在
在實時應用程序中,檢測客戶端何時連接和斷開連接通常很有用。例如,您可能希望在客戶端斷開連接時將用戶標記為“離線”。
Firebase 數據庫客戶端提供簡單的原語,當客戶端與 Firebase 數據庫服務器斷開連接時,您可以使用這些原語寫入數據庫。無論客戶端是否完全斷開連接,這些更新都會發生,因此即使連接斷開或客戶端崩潰,您也可以依靠它們來清理數據。所有寫操作,包括設置、更新和刪除,都可以在斷開連接時執行。
以下是使用onDisconnect
原語在斷開連接時寫入數據的簡單示例:
迅速
let presenceRef = Database.database().reference(withPath: "disconnectmessage"); // Write a string when this client loses connection presenceRef.onDisconnectSetValue("I disconnected!")
Objective-C
FIRDatabaseReference *presenceRef = [[FIRDatabase database] referenceWithPath:@"disconnectmessage"]; // Write a string when this client loses connection [presenceRef onDisconnectSetValue:@"I disconnected!"];
onDisconnect 的工作原理
當您建立onDisconnect()
操作時,該操作位於 Firebase 實時數據庫服務器上。服務器檢查安全性以確保用戶可以執行請求的寫入事件,並通知您的應用程序(如果該事件無效)。然後服務器監視連接。如果連接在任何時候超時,或者被實時數據庫客戶端主動關閉,服務器會再次檢查安全性(以確保操作仍然有效),然後調用該事件。
您的應用程序可以在寫入操作上使用回調來確保onDisconnect
已正確附加:
迅速
presenceRef.onDisconnectRemoveValue { error, reference in if let error = error { print("Could not establish onDisconnect event: \(error)") } }
Objective-C
[presenceRef onDisconnectRemoveValueWithCompletionBlock:^(NSError *error, FIRDatabaseReference *reference) { if (error != nil) { NSLog(@"Could not establish onDisconnect event: %@", error); } }];
onDisconnect
事件也可以通過調用.cancel()
取消:
迅速
presenceRef.onDisconnectSetValue("I disconnected") // some time later when we change our minds presenceRef.cancelDisconnectOperations()
Objective-C
[presenceRef onDisconnectSetValue:@"I disconnected"]; // some time later when we change our minds [presenceRef cancelDisconnectOperations];
檢測連接狀態
對於許多與狀態相關的功能,您的應用程序了解其何時在線或離線非常有用。 Firebase 實時數據庫在/.info/connected
中提供了一個特殊位置,每次 Firebase 實時數據庫客戶端的連接狀態發生變化時,該位置都會更新。這是一個例子:
迅速
let connectedRef = Database.database().reference(withPath: ".info/connected") connectedRef.observe(.value, with: { snapshot in if snapshot.value as? Bool ?? false { print("Connected") } else { print("Not connected") } })
Objective-C
FIRDatabaseReference *connectedRef = [[FIRDatabase database] referenceWithPath:@".info/connected"]; [connectedRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) { if([snapshot.value boolValue]) { NSLog(@"connected"); } else { NSLog(@"not connected"); } }];
/.info/connected
是一個布爾值,在實時數據庫客戶端之間不同步,因為該值取決於客戶端的狀態。換句話說,如果一個客戶端將/.info/connected
讀取為 false,則不能保證另一客戶端也會讀取 false。
處理延遲
服務器時間戳
Firebase 實時數據庫服務器提供了一種將服務器上生成的時間戳作為數據插入的機制。此功能與onDisconnect
相結合,提供了一種簡單的方法來可靠地記錄實時數據庫客戶端斷開連接的時間:
迅速
let userLastOnlineRef = Database.database().reference(withPath: "users/morgan/lastOnline") userLastOnlineRef.onDisconnectSetValue(ServerValue.timestamp())
Objective-C
FIRDatabaseReference *userLastOnlineRef = [[FIRDatabase database] referenceWithPath:@"users/morgan/lastOnline"]; [userLastOnlineRef onDisconnectSetValue:[FIRServerValue timestamp]];
時鐘偏差
雖然firebase.database.ServerValue.TIMESTAMP
更加準確,並且對於大多數讀/寫操作來說更可取,但它有時可以用於估計客戶端相對於 Firebase 實時數據庫服務器的時鐘偏差。您可以將回調附加到位置/.info/serverTimeOffset
來獲取 Firebase 實時數據庫客戶端添加到本地報告時間(紀元時間,以毫秒為單位)的值(以毫秒為單位)以估計服務器時間。請注意,此偏移的準確性可能會受到網絡延遲的影響,因此主要用於發現時鐘時間中的較大(> 1 秒)差異。
迅速
let offsetRef = Database.database().reference(withPath: ".info/serverTimeOffset") offsetRef.observe(.value, with: { snapshot in if let offset = snapshot.value as? TimeInterval { print("Estimated server time in milliseconds: \(Date().timeIntervalSince1970 * 1000 + offset)") } })
Objective-C
FIRDatabaseReference *offsetRef = [[FIRDatabase database] referenceWithPath:@".info/serverTimeOffset"]; [offsetRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) { NSTimeInterval offset = [(NSNumber *)snapshot.value doubleValue]; NSTimeInterval estimatedServerTimeMs = [[NSDate date] timeIntervalSince1970] * 1000.0 + offset; NSLog(@"Estimated server time: %0.3f", estimatedServerTimeMs); }];
狀態應用程序示例
通過將斷開連接操作與連接狀態監控和服務器時間戳相結合,您可以構建用戶存在系統。在此系統中,每個用戶將數據存儲在數據庫位置以指示實時數據庫客戶端是否在線。客戶端在上線時將此位置設置為 true,在斷開連接時設置時間戳。該時間戳表示給定用戶上次在線的時間。
請注意,您的應用程序應在將用戶標記為在線之前對斷開連接操作進行排隊,以避免在兩個命令發送到服務器之前客戶端網絡連接丟失的情況下出現任何競爭條件。
這是一個簡單的用戶存在系統:
迅速
// since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline let myConnectionsRef = Database.database().reference(withPath: "users/morgan/connections") // stores the timestamp of my last disconnect (the last time I was seen online) let lastOnlineRef = Database.database().reference(withPath: "users/morgan/lastOnline") let connectedRef = Database.database().reference(withPath: ".info/connected") connectedRef.observe(.value, with: { snapshot in // only handle connection established (or I've reconnected after a loss of connection) guard let connected = snapshot.value as? Bool, connected else { return } // add this device to my connections list let con = myConnectionsRef.childByAutoId() // when this device disconnects, remove it. con.onDisconnectRemoveValue() // The onDisconnect() call is before the call to set() itself. This is to avoid a race condition // where you set the user's presence to true and the client disconnects before the // onDisconnect() operation takes effect, leaving a ghost user. // this value could contain info about the device or a timestamp instead of just true con.setValue(true) // when I disconnect, update the last time I was seen online lastOnlineRef.onDisconnectSetValue(ServerValue.timestamp()) })
Objective-C
// since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline FIRDatabaseReference *myConnectionsRef = [[FIRDatabase database] referenceWithPath:@"users/morgan/connections"]; // stores the timestamp of my last disconnect (the last time I was seen online) FIRDatabaseReference *lastOnlineRef = [[FIRDatabase database] referenceWithPath:@"users/morgan/lastOnline"]; FIRDatabaseReference *connectedRef = [[FIRDatabase database] referenceWithPath:@".info/connected"]; [connectedRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) { if([snapshot.value boolValue]) { // connection established (or I've reconnected after a loss of connection) // add this device to my connections list FIRDatabaseReference *con = [myConnectionsRef childByAutoId]; // when this device disconnects, remove it [con onDisconnectRemoveValue]; // The onDisconnect() call is before the call to set() itself. This is to avoid a race condition // where you set the user's presence to true and the client disconnects before the // onDisconnect() operation takes effect, leaving a ghost user. // this value could contain info about the device or a timestamp instead of just true [con setValue:@YES]; // when I disconnect, update the last time I was seen online [lastOnlineRef onDisconnectSetValue:[FIRServerValue timestamp]]; } }];