FirebaseFirestore Framework Reference

Firestore

classFirestore:NSObject

Firestore represents a Firestore Database and is the entry point for all Firestoreoperations.

  • Creates, caches, and returns the defaultFirestore using the defaultFirebaseApp. Each subsequent invocation returns the sameFirestore object.

    Declaration

    Swift

    classfuncfirestore()->Self

    Return Value

    The defaultFirestore instance.

  • Creates, caches, and returns the defaultFirestore object for the specifiedapp. Each subsequent invocation returns the sameFirestore object.

    Declaration

    Swift

    classfuncfirestore(app:FIRApp)->Self

    Parameters

    app

    TheFirebaseApp instance to use for authentication and as a source of the GoogleCloud Project ID for your Firestore Database. If you want the default instance, you shouldexplicitly set it toFirebaseApp.app().

    Return Value

    The defaultFirestore instance.

  • This method is in preview. API signature and functionality are subject to change.

    Creates, caches, and returns namedFirestore object for the specifiedFirebaseApp. Each subsequent invocation returns the sameFirestore object.

    Declaration

    Swift

    classfuncfirestore(app:FIRApp,database:String)->Self

    Parameters

    app

    TheFirebaseApp instance to use for authentication and as a source of the GoogleCloud Project ID for your Firestore Database. If you want the default instance, you shouldexplicitly set it toFirebaseApp.app().

    database

    The database name.

    Return Value

    The namedFirestore instance.

  • This method is in preview. API signature and functionality are subject to change.

    Creates, caches, and returns namedFirestore object for the defaultapp. Each subsequent invocation returns the sameFirestore object.

    Declaration

    Swift

    classfuncfirestore(database:String)->Self

    Parameters

    database

    The database name.

    Return Value

    The namedFirestore instance.

  • Custom settings used to configure thisFirestore object.

    Declaration

    Swift

    @NSCopyingvarsettings:FIRFirestoreSettings{getset}
  • The Firebase App associated with this Firestore instance.

    Declaration

    Swift

    varapp:FIRApp{get}
  • A PersistentCacheIndexManager which you can config persistent cache indexes used forlocal query execution.

    Declaration

    Swift

    varpersistentCacheIndexManager:FIRPersistentCacheIndexManager?{get}
  • Deprecated

    Instead of creating cache indexes manually, consider usingPersistentCacheIndexManager.enableIndexAutoCreation() to let the SDK decide whether to create cache indexes for queries running locally.

    NOTE: This preview method will be deprecated in a future major release. Consider usingPersistentCacheIndexManager.enableIndexAutoCreation() to let the SDK decide whether to create cache indexes for queries running locally.

    Configures indexing for local query execution. Any previous index configuration is overridden.

    The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.

    The method accepts the JSON format exported by the Firebase CLI (firebase firestore:indexes). If the JSON format is invalid, the completion block will be invoked with an NSError.

    Declaration

    Swift

    funcsetIndexConfiguration(_json:String)asyncthrows

    Parameters

    json

    The JSON format exported by the Firebase CLI.

    completion

    A block to execute when setting is in a final state. Theerror parameterwill be set if the block is invoked due to an error.

  • Deprecated

    Instead of creating cache indexes manually, consider usingPersistentCacheIndexManager.enableIndexAutoCreation() to let the SDK decide whether to create cache indexes for queries running locally.

    NOTE: This preview method will be deprecated in a future major release. Consider usingPersistentCacheIndexManager.enableIndexAutoCreation() to let the SDK decide whether to create cache indexes for queries running locally.

    Configures indexing for local query execution. Any previous index configuration is overridden.

    The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.

    Indexes are only supported with LevelDB persistence. Invokeset_persistence_enabled(true) before setting an index configuration. If LevelDB is not enabled, any index configuration will be rejected.

    The method accepts the JSON format exported by the Firebase CLI (firebase firestore:indexes). If the JSON format is invalid, this method ignores the changes.

    Declaration

    Swift

    funcsetIndexConfiguration(_stream:InputStream)asyncthrows

    Parameters

    stream

    An input stream from which the configuration can be read.

    completion

    A block to execute when setting is in a final state. Theerror parameterwill be set if the block is invoked due to an error.

  • Gets aCollectionReference referring to the collection at the specified path within the database.

    Declaration

    Swift

    funccollection(_collectionPath:String)->FIRCollectionReference

    Parameters

    collectionPath

    The slash-separated path of the collection for which to get aCollectionReference.

    Return Value

    TheCollectionReference at the specifiedcollectionPath.

  • Gets aDocumentReference referring to the document at the specified path within the database.

    Declaration

    Swift

    funcdocument(_documentPath:String)->FIRDocumentReference

    Parameters

    documentPath

    The slash-separated path of the document for which to get aDocumentReference.

    Return Value

    TheDocumentReference for the specifieddocumentPath.

  • Creates and returns a newQuery that includes all documents in the database that are contained in a collection or subcollection with the given collectionID.

    Declaration

    Swift

    funccollectionGroup(_collectionID:String)->FIRQuery

    Parameters

    collectionID

    Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.

    Return Value

    The createdQuery.

  • Executes the given updateBlock and then attempts to commit the changes applied within an atomic transaction.

    The maximum number of writes allowed in a single transaction is 500, but note that each usage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a transaction counts as an additional write.

    In the updateBlock, a set of reads and writes can be performed atomically using theTransaction object passed to the block. After the updateBlock is run, Firestore will attempt to apply the changes to the server. If any of the data read has been modified outside of this transaction since being read, then the transaction will be retried by executing the updateBlock again. If the transaction still fails after 5 retries, then the transaction will fail.

    Since the updateBlock may be executed multiple times, it should avoiding doing anything that would cause side effects.

    Any value maybe be returned from the updateBlock. If the transaction is successfully committed, then the completion block will be passed that value. The updateBlock also has anNSErrorPointer out parameter. If this is set, then the transaction will not attempt to commit, and the given error will be passed to the completion block.

    TheTransaction object passed to the updateBlock contains methods for accessing documents and collections. Unlike other firestore access, data accessed with the transaction will not reflect local changes that have not been committed. For this reason, it is required that all reads are performed before any writes. Transactions must be performed while online. Otherwise, reads will fail, the final commit will fail, and the completion block will return an error.

    Declaration

    Swift

    funcrunTransaction(_updateBlock:@escaping(FIRTransaction,NSErrorPointer)->Any?,completion:@escaping(Any?,(anyError)?)->Void)

    Parameters

    updateBlock

    The block to execute within the transaction context.

    completion

    The block to call with the result or error of the transaction. This block will run even if the client is offline, unless the process is killed.

  • Executes the given updateBlock and then attempts to commit the changes applied within an atomic transaction.

    The maximum number of writes allowed in a single transaction is 500, but note that each usage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a transaction counts as an additional write.

    In the updateBlock, a set of reads and writes can be performed atomically using theTransaction object passed to the block. After the updateBlock is run, Firestore will attempt to apply the changes to the server. If any of the data read has been modified outside of this transaction since being read, then the transaction will be retried by executing the updateBlock again. If the transaction still fails after the attempting the number of times specified by themax_attempts property of the givenTransactionOptions object, then the transaction will fail. If the givenTransactionOptions isnil, then the defaultmax_attempts of 5 will be used.

    Since the updateBlock may be executed multiple times, it should avoiding doing anything that would cause side effects.

    Any value maybe be returned from the updateBlock. If the transaction is successfully committed, then the completion block will be passed that value. The updateBlock also has anNSErrorPointer out parameter. If this is set, then the transaction will not attempt to commit, and the given error will be passed to the completion block.

    TheTransaction object passed to the updateBlock contains methods for accessing documents and collections. Unlike other firestore access, data accessed with the transaction will not reflect local changes that have not been committed. For this reason, it is required that all reads are performed before any writes. Transactions must be performed while online. Otherwise, reads will fail, the final commit will fail, and the completion block will return an error.

    Declaration

    Swift

    funcrunTransaction(withoptions:FIRTransactionOptions?,blockupdateBlock:@escaping(FIRTransaction,NSErrorPointer)->Any?,completion:@escaping(Any?,(anyError)?)->Void)

    Parameters

    options

    The transaction options for controlling execution, ornil to use the default transaction options.

    updateBlock

    The block to execute within the transaction context.

    completion

    The block to call with the result or error of the transaction. This block will run even if the client is offline, unless the process is killed.

  • Creates a write batch, used for performing multiple writes as a single atomic operation.

    The maximum number of writes allowed in a single batch is 500, but note that each usage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a batch counts as an additional write.

    Unlike transactions, write batches are persisted offline and therefore are preferable when you don’t need to condition your writes on read data.

    Declaration

    Swift

    funcbatch()->FIRWriteBatch
  • Enables or disables logging from the Firestore client.

    Declaration

    Swift

    classfuncenableLogging(_logging:Bool)
  • Configures Firestore to connect to an emulated host instead of the default remote backend. AfterFirestore has been used (i.e. a document reference has been instantiated), this value cannot bechanged.

    Declaration

    Swift

    funcuseEmulator(withHosthost:String,port:Int)
  • Re-enables usage of the network by this Firestore instance after a prior call todisableNetwork(completion:). Completion block, if provided, will be called once network uasgehas been enabled.

    Declaration

    Swift

    funcenableNetwork()asyncthrows
  • Disables usage of the network by this Firestore instance. It can be re-enabled by viaenableNetwork. While the network is disabled, any snapshot listeners or get calls will returnresults from cache and any write operations will be queued until the network is restored. Thecompletion block, if provided, will be called once network usage has been disabled.

    Declaration

    Swift

    funcdisableNetwork()asyncthrows
  • Clears the persistent storage. This includes pending writes and cached documents.

    Must be called while the firestore instance is not started (after the app is shutdown or when the app is first initialized). On startup, this method must be called before other methods (other thanFirestore.settings). If the firestore instance is still running, the function will complete with an error code ofFailedPrecondition.

    Note:clearPersistence(completion:) is primarily intended to help write reliable tests that use Firestore. It uses the most efficient mechanism possible for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cache data in between user sessions we strongly recommend not to enable persistence in the first place.

    Declaration

    Swift

    funcclearPersistence()asyncthrows
  • Waits until all currently pending writes for the active user have been acknowledged by the backend.

    The completion block is called immediately without error if there are no outstanding writes. Otherwise, the completion block is called when all previously issued writes (including those written in a previous app session) have been acknowledged by the backend. The completion block does not wait for writes that were added after the method is called. If you wish to wait for additional writes, you have to callwaitForPendingWrites again.

    Any outstandingwaitForPendingWrites(completion:) completion blocks are called with an error during user change.

    Declaration

    Swift

    funcwaitForPendingWrites()asyncthrows
  • Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.

    NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.

    Declaration

    Swift

    funcaddSnapshotsInSyncListener(_listener:@escaping()->Void)->anyListenerRegistration

    Parameters

    listener

    A callback to be called every time all snapshot listeners are in sync with eachother.

    Return Value

    AListenerRegistration object that can be used to remove the listener.

  • Terminates thisFirestore instance.

    After callingterminate only theclearPersistence method may be used. Any other method will throw an error.

    To restart after termination, simply create a new instance ofFirestore with thefirestore method.

    Termination does not cancel any pending writes and any tasks that are awaiting a response from the server will not be resolved. The next time you start this instance, it will resume attempting to send these writes to the server.

    Note: Under normal circumstances, calling this method is not required. This method is useful only when you want to force this instance to release all of its resources or in combination withclearPersistence to ensure that all local state is destroyed between test runs.

    Declaration

    Swift

    functerminate()asyncthrows

    Parameters

    completion

    A block to execute once everything has been terminated.

  • Loads a Firestore bundle into the local cache.

    Declaration

    Swift

    funcloadBundle(_bundleData:Data)->FIRLoadBundleTask

    Parameters

    bundleData

    Data from the bundle to be loaded.

    Return Value

    ALoadBundleTask which allows registered observersto receive progress updates and completion or error events.

  • Loads a Firestore bundle into the local cache.

    Declaration

    Swift

    funcloadBundle(_bundleData:Data,completion:((FIRLoadBundleTaskProgress?,(anyError)?)->Void)?=nil)->FIRLoadBundleTask

    Parameters

    bundleData

    Data from the bundle to be loaded.

    completion

    A block to execute when loading is in a final state. Theerror parameterwill be set if the block is invoked due to an error. If observers are registered to theLoadBundleTask, this block will be called after all observers are notified.

    Return Value

    ALoadBundleTask which allows registered observers to receive progress updates andcompletion or error events.

  • Loads a Firestore bundle into the local cache.

    Declaration

    Swift

    funcloadBundle(_bundleStream:InputStream)->FIRLoadBundleTask

    Parameters

    bundleStream

    An input stream from which the bundle can be read.

    Return Value

    ALoadBundleTask which allows registered observers to receive progress updates andcompletion or error events.

  • Loads a Firestore bundle into the local cache.

    Declaration

    Swift

    funcloadBundle(_bundleStream:InputStream,completion:((FIRLoadBundleTaskProgress?,(anyError)?)->Void)?=nil)->FIRLoadBundleTask

    Parameters

    bundleStream

    An input stream from which the bundle can be read.

    completion

    A block to execute when the loading is in a final state. Theerror parameterof the block will be set if it is due to an error. If observers are registered to the returningLoadBundleTask, this block will be called after all observers are notified.

    Return Value

    ALoadBundleTask which allow registering observers to receive progress updates, andcompletion or error events.

  • Reads aQuery from the local cache, identified by the given name.

    Named queries are packaged into bundles on the server side (along with the resulting documents) and loaded into local cache usingloadBundle. Once in the local cache, you can use this method to extract a query by name.

    Declaration

    Swift

    funcgetQuery(namedname:String)async->FIRQuery?

    Parameters

    completion

    A block to execute with the query read from the local cache. If no query can befound, its parameter will benil.

  • Loads a Firestore bundle into the local cache.

    Throws

    Error if the bundle data cannot be parsed.

    Declaration

    Swift

    funcloadBundle(_bundleData:Data)asyncthrows->LoadBundleTaskProgress

    Parameters

    bundleData

    Data from the bundle to be loaded.

    Return Value

    The finalLoadBundleTaskProgress that contains the total number of documentsloaded.

  • Loads a Firestore bundle into the local cache.

    Throws

    Error if the bundle stream cannot be parsed.

    Declaration

    Swift

    funcloadBundle(_bundleStream:InputStream)asyncthrows->LoadBundleTaskProgress

    Parameters

    bundleStream

    An input stream from which the bundle can be read.

    Return Value

    The finalLoadBundleTaskProgress that contains the total number of documentsloaded.

  • Executes the given updateBlock and then attempts to commit the changes applied within anatomictransaction.

    The maximum number of writes allowed in a single transaction is 500, but note that eachusage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a transaction counts as an additional write.

    In theupdateBlock, a set of reads and writes can be performed atomically using theTransaction object passed to the block. After theupdateBlock is run, Firestore willattemptto apply the changes to the server. If any of the data read has been modified outside ofthistransaction since being read, then the transaction will be retried by executing theupdateBlockagain. If the transaction still fails after 5 retries, then the transaction will fail.

    Since theupdateBlock may be executed multiple times, it should avoiding doing anythingthatwould cause side effects.

    Any value maybe be returned from theupdateBlock. If the transaction is successfullycommitted,then the completion block will be passed that value. TheupdateBlock also has anNSErroroutparameter. If this is set, then the transaction will not attempt to commit, and the givenerrorwill be returned.

    TheTransaction object passed to theupdateBlock contains methods for accessingdocumentsand collections. Unlike other firestore access, data accessed with the transaction will notreflect local changes that have not been committed. For this reason, it is required that allreads are performed before any writes. Transactions must be performed while online.Otherwise,reads will fail, the final commit will fail, and this function will return an error.

    Throws

    Throws Throws an error if the transaction could not be committed, or if an error wasexplicitly specified in theupdateBlock parameter.

    Declaration

    Swift

    funcrunTransaction(_updateBlock:@escaping(Transaction,NSErrorPointer)->Any?)asyncthrows->Any?
  • Undocumented

    Declaration

    Swift

    classEncoder
  • Undocumented

    Declaration

    Swift

    classDecoder

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-03-11 UTC.