Accedere ai dati offline

Cloud Firestore supporta la persistenza dei dati offline. Questa funzionalità memorizza nella cache una copia degli dati Cloud Firestore usati attivamente dalla tua app, in modo che l'app possa accedere ai dati quando il dispositivo è offline. Puoi scrivere, leggere, ascoltare ed eseguire query sui dati memorizzati nella cache. Quando il dispositivo torna online, Cloud Firestore sincronizza le modifiche locali apportate dall'app con il backend di Cloud Firestore.

Per utilizzare la persistenza offline, non è necessario apportare modifiche al codice utilizzato per accedere ai dati di Cloud Firestore. Con la persistenza offline attivata, la libreria client Cloud Firestore gestisce automaticamente l'accesso ai dati online e offline e sincronizza i dati locali quando il dispositivo è di nuovo online.

Configura la persistenza offline

Quando avvii Cloud Firestore, puoi attivare o disattivare la persistenza offline:

  • Per le piattaforme Android e Apple, la persistenza offline è abilitata per impostazione predefinita. Per disattivare la persistenza, imposta l'opzione PersistenceEnabled su false.
  • Per il web, la persistenza offline è disabilitata per impostazione predefinita. Per attivare la persistenza, chiama il metodo enablePersistence. La cache di Cloud Firestore non viene cancellata automaticamente tra le sessioni. Di conseguenza, se la tua app web gestisce informazioni sensibili, assicurati di chiedere all'utente se utilizza un dispositivo attendibile prima di attivare la persistenza.

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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
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+KTX

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));

Configura la dimensione della cache

Quando la persistenza è attivata, Cloud Firestore memorizza nella cache ogni documento ricevuto dal backend per l'accesso offline. Cloud Firestore imposta una soglia predefinita per le dimensioni della cache. Una volta superata la soglia predefinita, Cloud Firestore tenta periodicamente di eliminare i dati meno recenti e inutilizzati documenti. Puoi configurare una soglia di dimensione della cache diversa o disattivare completamente il processo di pulizia:

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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
// 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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
// 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+KTX


// 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,
);

Ascolta i dati offline

Quando il dispositivo è offline, se hai abilitato la persistenza offline, il I listener riceveranno eventi di ascolto quando i dati memorizzati nella cache locale vengono modificati. Tu può ascoltare documenti, raccolte e query.

Per verificare se i dati vengono ricevuti dal server o dalla cache, utilizza la Proprietà fromCache in SnapshotMetadata nel tuo evento snapshot. Se fromCache è true, i dati provengono dalla cache e potrebbero essere inattivi o incompleta. Se fromCache è false, i dati sono completi e aggiornati con gli ultimi aggiornamenti sul server.

Per impostazione predefinita, non viene generato alcun evento se è cambiato soloSnapshotMetadata SnapshotMetadata. Se ti basi sui valori fromCache, specifica l'opzione di ascolto includeMetadataChanges quando colleghi il gestore di ascolto.

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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
// 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
Nota: questo prodotto non è disponibile su watchOS e sui target di App Clip.
// 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+KTX

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}");
    }
  }
});

Ottenere dati offline

Se ricevi un documento mentre il dispositivo è offline, Cloud Firestore restituisce i dati dalla cache.

Quando esegui una query su una raccolta, viene restituito un risultato vuoto se non sono presenti documenti memorizzati nella cache. Durante il recupero di un documento specifico, viene invece restituito un errore.

Eseguire query sui dati offline

L'esecuzione di query funziona con la persistenza offline. Puoi recuperare i risultati delle query con un comando "get" diretto o "ascoltando", come descritto sezioni. Puoi anche creare nuove query su dati persistenti localmente dispositivo è offline, ma inizialmente le query verranno eseguite solo sulla cache documenti.

Configura gli indici delle query offline

Per impostazione predefinita, l'SDK Firestore analizza tutti i documenti di una raccolta nel suo cache locale durante l'esecuzione di query offline. Con questo comportamento predefinito, le prestazioni delle query possono risentirne se gli utenti sono offline per lunghi periodi di tempo.

Se la cache persistente è abilitata, puoi migliorare le prestazioni della navigazione offline consentendo all'SDK di creare automaticamente indici di query locali.

L'indicizzazione automatica è disabilitata per impostazione predefinita. L'app deve attivare l'indicizzazione automatica a ogni avvio. Controlla se l'indicizzazione automatica è attivata come mostrato di seguito.

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+KTX

// 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();
    

Una volta attivata l'indicizzazione automatica, l'SDK valuta quali raccolte hanno un numero elevato di documenti memorizzati nella cache e ottimizza le prestazioni delle query locali.

L'SDK fornisce un metodo per eliminare gli indici di query.

Disattivare e attivare l'accesso alla rete

Puoi utilizzare il metodo riportato di seguito per disattivare l'accesso alla rete per il tuo client Cloud Firestore. Quando l'accesso alla rete è disattivato, tutti gli ascoltatori di snapshot e le richieste di documenti recuperano i risultati dalla cache. Le operazioni di scrittura vengono messe in coda fino a quando l'accesso alla rete non viene riattivato.

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
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
Firestore.firestore().disableNetwork { (error) in
  // Do offline things
  // ...
}
Objective-C
Nota: questo prodotto non è disponibile su watchOS e sui target di App Clip.
[[FIRFirestore firestore] disableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do offline actions
  // ...
}];

Kotlin+KTX

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
});

Per riattivare l'accesso alla rete, utilizza il seguente metodo:

Web

import { enableNetwork } from "firebase/firestore"; 

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

Web

firebase.firestore().enableNetwork()
    .then(() => {
        // Do online actions
        // ...
    });
Swift
Nota: questo prodotto non è disponibile come target per watchOS e App Clip.
Firestore.firestore().enableNetwork { (error) in
  // Do online things
  // ...
}
Objective-C
Nota: questo prodotto non è disponibile su watchOS e sui target di App Clip.
[[FIRFirestore firestore] enableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do online actions
  // ...
}];

Kotlin+KTX

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
});