Search code examples
iosswiftfirebaseasynchronouspromisekit

Firebase calls with PromiseKit/AwaitKit in Swift never returns


Similarly to this unanswered question, I have been unable to use Firebase Auth and Database calls with a Promise in Swift. I am able use such calls in a completion handler like this (as long as the completion handler isn't within a Promise):

Database.database().reference(withPath: "/Path/To/My/Data").observeSingleEvent(of: .value, with: { (result) in
    // do things with the result
})

But not like this (I am using AwaitKit to wait for the promise to finish):

func getData(from path: String) -> Promise<DataSnapshot> {
    let ref = Database.database().reference(withPath: path)

    return Promise { (fulfill, reject) in
        ref.observeSingleEvent(of: .value, with: { (result) in
            fulfill(result) // this is never called
        })
    }
}

await(getData(from: "/Path/To/My/Data")) // this never completes

When I call await(getData(from: "/Path/To/My/Data")), the call never completes and the rest of the code after the call never executes. The same issue occurs when trying to authenticate using the Auth.auth().signInAnonymously(completion:) method; it works perfectly fine by itself but never returns when inside a promise. After running for about a minute, both calls automatically terminate with the following message in the console:

TIC TCP Conn Failed [6:0x12190e8b0]: 3:-9802 Err(-9802)

I'm thinking that the issue may lie in the fact that AwaitKit uses semaphores to wait for the promise to fulfill, but I'm not entirely sure.

So how can I successfully use Firebase from within a promise? Thanks for the help!


Solution

  • Adding async around the await call fixed my issue, like so:

    async {
        await(getData(from: "/Path/To/My/Data"))
        // continue execution
    }