【问题标题】:How to set value to Firebase Realtime Database in background?如何在后台为 Firebase 实时数据库设置值?
【发布时间】:2017-01-10 10:15:44
【问题描述】:

我这样在后台调用 setValue():

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0)
    let ref = FIRDatabase.database().reference().child("data")
    let data: NSDictionary = [
        "test" : "test"
    ]
    ref.setValue(data, withCompletionBlock:{
        (error, reference) in
        if error != nil {
            print(error!)
        } else {
            print("success")
            semaphore.signal()  
        }
    })
    _ = semaphore.wait(timeout: .distantFuture)
    completionHandler(.newData)
}

但从未调用完成块。后台不能上传数据吗?

【问题讨论】:

  • 遇到了同样的问题。对其他服务器的 POST 请求在后台工作,但 Firebase 什么都不做
  • 这个@Shangri-La 有更新吗?我尝试了@DimaRostopira 的建议,但没有成功。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

Apple 允许在后台调用少数功能

  1. 麦克风
  2. 位置更新
  3. 蓝牙配件
  4. 网络电话

【讨论】:

  • 但是我们可以在后台从数据库中获取数据。
【解决方案2】:

keepSynced(true) 帮了我大忙,只需添加到您的代码中

let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0)
let ref = FIRDatabase.database().reference().child("data")
let data: NSDictionary = [
    "test" : "test"
]
ref.keepSynced(true)
ref.setValue(data, withCompletionBlock:{
    (error, reference) in
    if error != nil {
        print(error!)
    } else {
        print("success")
        semaphore.signal()  
    }
})
_ = semaphore.wait(timeout: .distantFuture)
completionHandler(.newData)

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2021-03-30
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多