How to handle timeout in queries with Firebase

前端 未结 5 1702
终归单人心
终归单人心 2021-01-02 04:35

I noticed that if I execute a query in Firebase and the database server is not reachable, the callback waits just forever (or until the server is reachable again).

W

5条回答
  •  自闭症患者
    2021-01-02 04:52

    I would suggest simply using a thread?

    Allow yourself to assign your call to Firebase from within a thread instance, then in the rare event that the write to Firebase takes too long you can just cancel the thread?

    let thread = NSThread(target:self, selector:#selector(uploadToFirebase), object:nil)
    

    . . .

    func uploadToFirebase(data: Dictionary) {
    
        // Do what you need to here. Just an example
    
        db.collection("posts").document("some unique post id").setData([
            "name": "John",
            "likes": 0
        ]) { err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                print("Document successfully written!")
            }
        }
    
    }
    

    Then just create a timer that cancels the thread if the timer fires. If not, just cancel the timer.

提交回复
热议问题