我有一个使用firebase来存储数据库的应用程序,我想在用户杀死该应用程序时清除名为current_venue的特定用户字段,为此,我正在使用AppDelegate方法applicationWillTerminate,并且在我杀死该应用程序时调用了它,但不是完全。

以下是我在AppDelegate中的代码:

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    WebServiceAPI.checkOutVenue()
}

另一种方法是:
static func checkOutVenue() {

    WebServiceAPI.sharedInstance.current_venue = ""
    if WebServiceAPI.sharedInstance.user == nil {
        return
    }
    let user = WebServiceAPI.sharedInstance.user!
    let ref = FIRDatabase.database().reference()
    ref.child("Clients").child(user.uid).child("current_venue").setValue("") { (err, venueIdRef) in
        if err == nil {
            WebServiceAPI.sharedInstance.current_venue = ""
        }
    }
}

我尝试调试它,如下图所示:

ios - Firebase:当用户杀死应用程序时,如何从Firebase中清除特定数据?-LMLPHP

当我杀死应用程序断点1和2时,但它从未到达断点3。

我从以下位置阅读文档:

https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623111-applicationwillterminate

其中说:

此方法的实现大约需要五秒钟来执行任何任务并返回。如果该方法在时间到期之前未返回,则系统可能会完全终止该过程。

实际上,从firebase清除该字段所需的时间不超过5秒。

打开应用程序时,相同的代码工作正常。

因此我的代码运行正常,但是在终止该应用程序时却缺少一些东西。

谢谢你的帮助。

最佳答案

确保在用户断开连接时清理数据的更好方法是使用onDisconnect处理程序。 Firebase documentation explains them,但这是一个如何使用它的简单示例:

ref.child("Clients")
   .child(user.uid)
   .child("current_venue")
   .onDisconnectRemoveValue()

执行此代码后,客户端断开连接时,指令将发送到服务器以删除节点。这意味着它将始终运行,即使客户端(甚至电话)崩溃并且客户端代码永远也没有机会执行。

09-27 01:22
查看更多