How to detect absent network connection when setting Firestore document

前端 未结 1 1765
谎友^
谎友^ 2020-12-11 07:08

We are building a real-time chat app using Firestore. We need to handle a situation when Internet connection is absent. Basic message sending code looks like this

相关标签:
1条回答
  • 2020-12-11 07:27

    The completion callbacks for Firestore are only called when the data has been written (or rejected) on the server. There is no callback for when there is no network connection, as this is considered a normal condition for the Firestore SDK.

    Your best option is to detect whether there is a network connection in another way, and then update your UI accordingly. Some relevant search results:

    • Check for internet connection with Swift
    • How to check for an active Internet connection on iOS or macOS?
    • Check for internet connection availability in Swift

    As an alternatively, you can check use Firestore's built-in metadata to determine whether messages have been delivered. As shown in the documentation on events for local changes:

    Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener:

    db.collection("cities").document("SF")
        .addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            let source = document.metadata.hasPendingWrites ? "Local" : "Server"
            print("\(source) data: \(document.data() ?? [:])")
        }
    

    With this you can also show the message correctly in the UI

    0 讨论(0)
提交回复
热议问题