גישה לנתונים במצב אופליין

Cloud Firestore תומך בנתונים מתמידים ממקורות אופליין. התכונה הזו שומרת במטמון עותק של נתוני Cloud Firestore שהאפליקציה שלכם משתמשת בהם באופן פעיל, כדי שהאפליקציה תוכל לגשת לנתונים כשהמכשיר במצב אופליין. אתם יכולים לכתוב, לקרוא, להאזין לנתונים שנשמרו במטמון ולשלוח להם שאילתות. כשהמכשיר חוזר למצב אונליין, ‫Cloud Firestore מתבצע סנכרון של כל השינויים המקומיים שבוצעו באפליקציה עם ‫Cloud Firestore ה-backend.

כדי להשתמש בנתונים שנשמרים במצב אופליין, לא צריך לבצע שינויים בקוד שמשמש לגישה לנתוני Cloud Firestore. כשהתכונה 'המשכיות במצב אופליין' מופעלת, ספריית הלקוח Cloud Firestore מנהלת באופן אוטומטי את הגישה לנתונים במצב אונליין ובמצב אופליין, ומסנכרנת את הנתונים המקומיים כשהמכשיר חוזר למצב אונליין.

הגדרת שמירה במצב אופליין

כשמפעילים את Cloud Firestore, אפשר להפעיל או להשבית את השמירה במצב אופליין:

  • בפלטפורמות Android ו-Apple, שמירת נתונים במצב אופליין מופעלת כברירת מחדל. כדי להשבית את ההתמדה, מגדירים את האפשרות PersistenceEnabled לערך false.
  • באינטרנט, שמירת נתונים במצב אופליין מושבתת כברירת מחדל. כדי להפעיל את ההתמדה, צריך לבצע קריאה ל-method‏ enablePersistence. המטמון של Cloud Firestore לא מתנקה אוטומטית בין סשנים. לכן, אם אפליקציית האינטרנט שלכם מטפלת במידע רגיש, הקפידו לשאול את המשתמש אם הוא משתמש במכשיר מהימן לפני שתפעילו את ההתמדה.

Web

// Memory cache is the default if no config is specified.
initializeFirestore(app);

// This is the default behavior if no persistence is specified.
initializeFirestore(app, {localCache: memoryLocalCache()});

// Defaults to single-tab persistence if no tab manager is specified.
initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})});

// Same as `initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})})`,
// but more explicit about tab management.
initializeFirestore(app, 
  {localCache: 
    persistentLocalCache(/*settings*/{tabManager: persistentSingleTabManager()})
});

// Use multi-tab IndexedDb persistence.
initializeFirestore(app, 
  {localCache: 
    persistentLocalCache(/*settings*/{tabManager: persistentMultipleTabManager()})
  });
  

Web

firebase.firestore().enablePersistence()
  .catch((err) => {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }
  });
// Subsequent queries will use persistence, if it was enabled successfully
Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
let settings = FirestoreSettings()

// Use memory-only cache
settings.cacheSettings =
MemoryCacheSettings(garbageCollectorSettings: MemoryLRUGCSettings())

// Use persistent disk cache, with 100 MB cache size
settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber)

// Any additional options
// ...

// Enable offline data persistence
let db = Firestore.firestore()
db.settings = settings
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
FIRFirestoreSettings *settings = [[FIRFirestoreSettings alloc] init];

// Use memory-only cache
settings.cacheSettings = [[FIRMemoryCacheSettings alloc]
    initWithGarbageCollectorSettings:[[FIRMemoryLRUGCSettings alloc] init]];

// Use persistent disk cache (default behavior)
// This example uses 100 MB.
settings.cacheSettings = [[FIRPersistentCacheSettings alloc]
    initWithSizeBytes:@(100 * 1024 * 1024)];

// Any additional options
// ...

// Enable offline data persistence
FIRFirestore *db = [FIRFirestore firestore];
db.settings = settings;

Kotlin

val settings = firestoreSettings {
    // Use memory cache
    setLocalCacheSettings(memoryCacheSettings {})
    // Use persistent disk cache (default)
    setLocalCacheSettings(persistentCacheSettings {})
}
db.firestoreSettings = settings

Java

FirebaseFirestoreSettings settings = 
new FirebaseFirestoreSettings.Builder(db.getFirestoreSettings())
    // Use memory-only cache
    .setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
    // Use persistent disk cache (default)
    .setLocalCacheSettings(PersistentCacheSettings.newBuilder()
                            .build())
    .build();
db.setFirestoreSettings(settings);

Dart

// Apple and Android
db.settings = const Settings(persistenceEnabled: true);

// Web
await db
    .enablePersistence(const PersistenceSettings(synchronizeTabs: true));

הגדרת גודל המטמון

כשהתכונה 'התמדה' מופעלת, Cloud Firestore שומר במטמון כל מסמך שהתקבל מהקצה העורפי לגישה אופליין. ‫Cloud Firestore מגדיר סף ברירת מחדל לגודל המטמון. אחרי שחורגים מהערך שמוגדר כברירת מחדל, Cloud Firestore מנסה מדי פעם למחוק מסמכים ישנים שלא נמצאים בשימוש. אפשר להגדיר סף שונה לגודל המטמון או להשבית לחלוטין את תהליך הניקוי:

Web

import { initializeFirestore, CACHE_SIZE_UNLIMITED } from "firebase/firestore";

const firestoreDb = initializeFirestore(app, {
  cacheSizeBytes: CACHE_SIZE_UNLIMITED
});

Web

firebase.firestore().settings({
    cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED
});
Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "FirestoreCacheSizeUnlimited"
// to disable clean-up.
let settings = Firestore.firestore().settings
// Set cache size to 100 MB
settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber)
Firestore.firestore().settings = settings
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "kFIRFirestoreCacheSizeUnlimited"
// to disable clean-up.
FIRFirestoreSettings *settings = [FIRFirestore firestore].settings;
// Set cache size to 100 MB
settings.cacheSettings =
    [[FIRPersistentCacheSettings alloc] initWithSizeBytes:@(100 * 1024 * 1024)];
[FIRFirestore firestore].settings = settings;
  

Kotlin


// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED"
// to disable clean-up.
val settings = FirebaseFirestoreSettings.Builder()
        .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
        .build()
db.firestoreSettings = settings

Java


// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED"
// to disable clean-up.
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
        .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
        .build();
db.setFirestoreSettings(settings);

Dart

db.settings = const Settings(
  persistenceEnabled: true,
  cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
);

האזנה לנתונים אופליין

אם הפעלתם את התכונה Offline persistence, בזמן שהמכשיר במצב אופליין, מאזינים יקבלו אירועי האזנה כשהנתונים ששמורים במטמון באופן מקומי ישתנו. אפשר להאזין למסמכים, לאוספים ולשאילתות.

כדי לבדוק אם אתם מקבלים נתונים מהשרת או מהמטמון, משתמשים במאפיין fromCache ב-SnapshotMetadata באירוע התמונה שלכם. אם fromCache הוא true, הנתונים הגיעו מהמטמון ויכול להיות שהם מיושנים או חלקיים. אם הערך של fromCache הוא false, הנתונים מלאים ועדכניים עם העדכונים האחרונים בשרת.

כברירת מחדל, לא מופעל אירוע אם רק SnapshotMetadata השתנה. אם אתם מסתמכים על הערכים של fromCache, צריך לציין את האפשרות includeMetadataChanges listen כשמצרפים את listen handler.

Web

import { collection, onSnapshot, where, query } from "firebase/firestore"; 

const q = query(collection(db, "cities"), where("state", "==", "CA"));
onSnapshot(q, { includeMetadataChanges: true }, (snapshot) => {
    snapshot.docChanges().forEach((change) => {
        if (change.type === "added") {
            console.log("New city: ", change.doc.data());
        }

        const source = snapshot.metadata.fromCache ? "local cache" : "server";
        console.log("Data came from " + source);
    });
});

Web

db.collection("cities").where("state", "==", "CA")
  .onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
      snapshot.docChanges().forEach((change) => {
          if (change.type === "added") {
              console.log("New city: ", change.doc.data());
          }

          var source = snapshot.metadata.fromCache ? "local cache" : "server";
          console.log("Data came from " + source);
      });
  });
Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
// Listen to metadata updates to receive a server snapshot even if
// the data is the same as the cached data.
db.collection("cities").whereField("state", isEqualTo: "CA")
  .addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in
    guard let snapshot = querySnapshot else {
      print("Error retreiving snapshot: \(error!)")
      return
    }

    for diff in snapshot.documentChanges {
      if diff.type == .added {
        print("New city: \(diff.document.data())")
      }
    }

    let source = snapshot.metadata.isFromCache ? "local cache" : "server"
    print("Metadata: Data fetched from \(source)")
  }
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
// Listen to metadata updates to receive a server snapshot even if
// the data is the same as the cached data.
[[[db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"]
    addSnapshotListenerWithIncludeMetadataChanges:YES
    listener:^(FIRQuerySnapshot *snapshot, NSError *error) {
      if (snapshot == nil) {
        NSLog(@"Error retreiving snapshot: %@", error);
        return;
      }
      for (FIRDocumentChange *diff in snapshot.documentChanges) {
        if (diff.type == FIRDocumentChangeTypeAdded) {
          NSLog(@"New city: %@", diff.document.data);
        }
      }

      NSString *source = snapshot.metadata.isFromCache ? @"local cache" : @"server";
      NSLog(@"Metadata: Data fetched from %@", source);
    }];

Kotlin

db.collection("cities").whereEqualTo("state", "CA")
    .addSnapshotListener(MetadataChanges.INCLUDE) { querySnapshot, e ->
        if (e != null) {
            Log.w(TAG, "Listen error", e)
            return@addSnapshotListener
        }

        for (change in querySnapshot!!.documentChanges) {
            if (change.type == DocumentChange.Type.ADDED) {
                Log.d(TAG, "New city: ${change.document.data}")
            }

            val source = if (querySnapshot.metadata.isFromCache) {
                "local cache"
            } else {
                "server"
            }
            Log.d(TAG, "Data fetched from $source")
        }
    }

Java

db.collection("cities").whereEqualTo("state", "CA")
        .addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot querySnapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w(TAG, "Listen error", e);
                    return;
                }

                for (DocumentChange change : querySnapshot.getDocumentChanges()) {
                    if (change.getType() == Type.ADDED) {
                        Log.d(TAG, "New city:" + change.getDocument().getData());
                    }

                    String source = querySnapshot.getMetadata().isFromCache() ?
                            "local cache" : "server";
                    Log.d(TAG, "Data fetched from " + source);
                }

            }
        });

Dart

db
    .collection("cities")
    .where("state", isEqualTo: "CA")
    .snapshots(includeMetadataChanges: true)
    .listen((querySnapshot) {
  for (var change in querySnapshot.docChanges) {
    if (change.type == DocumentChangeType.added) {
      final source =
          (querySnapshot.metadata.isFromCache) ? "local cache" : "server";

      print("Data fetched from $source}");
    }
  }
});

קבלת נתונים אופליין

אם מקבלים מסמך כשהמכשיר במצב אופליין, Cloud Firestore מחזיר נתונים מהמטמון.

כשמבצעים שאילתה על אוסף, אם אין מסמכים במטמון, מוחזרת תוצאה ריקה. כשמנסים לאחזר מסמך ספציפי, מוחזרת שגיאה במקום זאת.

שליחת שאילתות לנתונים ממקורות אופליין

השאילתות פועלות עם שמירה במצב אופליין. אפשר לאחזר את תוצאות השאילתות באמצעות בקשת GET ישירה או באמצעות האזנה, כמו שמתואר בקטעים הקודמים. אפשר גם ליצור שאילתות חדשות על נתונים שנשמרו באופן מקומי בזמן שהמכשיר במצב אופליין, אבל השאילתות יופעלו בהתחלה רק על המסמכים שנשמרו במטמון.

הגדרת אינדקסים של שאילתות אופליין

כברירת מחדל, ערכת ה-SDK של Firestore סורקת את כל המסמכים באוסף במטמון המקומי שלה כשמבצעים שאילתות במצב אופליין. בגלל התנהגות ברירת המחדל הזו, הביצועים של שאילתות במצב אופליין עלולים להיפגע אם המשתמשים נמצאים במצב אופליין למשך תקופות ארוכות.

אם מפעילים את האפשרות 'שמירת מטמון', אפשר לשפר את הביצועים של שאילתות אופליין על ידי מתן הרשאה ל-SDK ליצור באופן אוטומטי אינדקסים מקומיים של שאילתות.

הוספת אינדקס אוטומטית מושבתת כברירת מחדל. האפליקציה צריכה להפעיל אינדוקס אוטומטי בכל פעם שהיא מופעלת. קובעים אם ההוספה האוטומטית לאינדקס מופעלת, כמו שמוצג בהמשך.

Swift
if let indexManager = Firestore.firestore().persistentCacheIndexManager {
  // Indexing is disabled by default
  indexManager.enableIndexAutoCreation()
} else {
  print("indexManager is nil")
}
    
Objective-C
PersistentCacheIndexManager *indexManager = [FIRFirestore firestore].persistentCacheIndexManager;
if (indexManager) {
  // Indexing is disabled by default
  [indexManager enableIndexAutoCreation];
}
    

Kotlin

// return type: PersistentCacheManager?

Firebase.firestore.persistentCacheIndexManager?.apply {
      // Indexing is disabled by default
      enableIndexAutoCreation()
    } ?: println("indexManager is null")
    

Java

// return type: @Nullable PersistentCacheIndexManager
PersistentCacheIndexManager indexManager = FirebaseFirestore.getInstance().getPersistentCacheIndexManager();
if (indexManager != null) {
  // Indexing is disabled by default
  indexManager.enableIndexAutoCreation();
}

// If not check indexManager != null, IDE shows warning: Method invocation 'enableIndexAutoCreation' may produce 'NullPointerException' 
FirebaseFirestore.getInstance().getPersistentCacheIndexManager().enableIndexAutoCreation();
    

אחרי שמפעילים את יצירת האינדקס האוטומטית, ה-SDK בודק אילו אוספים מכילים מספר גדול של מסמכים במטמון, ומבצע אופטימיזציה של הביצועים של שאילתות מקומיות.

ערכת ה-SDK מספקת שיטה למחיקת אינדקסים של שאילתות.

השבתה והפעלה של גישה לרשת

אפשר להשתמש בשיטה הבאה כדי להשבית את הגישה לרשת עבור לקוח Cloud Firestore. כשהגישה לרשת מושבתת, כל מאזיני הצילום ובקשות המסמכים מאחזרים תוצאות מהמטמון. פעולות כתיבה מתווספות לתור עד שהגישה לרשת מופעלת מחדש.

Web

import { disableNetwork } from "firebase/firestore"; 

await disableNetwork(db);
console.log("Network disabled!");
// Do offline actions
// ...

Web

firebase.firestore().disableNetwork()
    .then(() => {
        // Do offline actions
        // ...
    });
Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
Firestore.firestore().disableNetwork { (error) in
  // Do offline things
  // ...
}
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
[[FIRFirestore firestore] disableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do offline actions
  // ...
}];

Kotlin

db.disableNetwork().addOnCompleteListener {
    // Do offline things
    // ...
}

Java

db.disableNetwork()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Do offline things
                // ...
            }
        });

Dart

db.disableNetwork().then((_) {
  // Do offline things
});

כדי להפעיל מחדש את הגישה לרשת, משתמשים בשיטה הבאה:

Web

import { enableNetwork } from "firebase/firestore"; 

await enableNetwork(db);
// Do online actions
// ...

Web

firebase.firestore().enableNetwork()
    .then(() => {
        // Do online actions
        // ...
    });
Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
Firestore.firestore().enableNetwork { (error) in
  // Do online things
  // ...
}
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
[[FIRFirestore firestore] enableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do online actions
  // ...
}];

Kotlin

db.enableNetwork().addOnCompleteListener {
    // Do online things
    // ...
}

Java

db.enableNetwork()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Do online things
                // ...
            }
        });

Dart

db.enableNetwork().then((_) {
  // Back online
});