gpt4 book ai didi

ios - Firebase:当用户终止应用程序时如何从 Firebase 中清除特定数据?

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:37 25 4
gpt4 key购买 nike

我有一个使用 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 = ""
}
}
}

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

enter image description here

当我终止应用程序时,断点 1 和 2 正在调用,但它从未到达断点 3。

我阅读了文档:

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

上面写着:

Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

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

当我打开应用程序时,相同的代码运行良好。

所以我的代码工作正常,但是当我终止应用程序时我遗漏了一些东西。

感谢您的帮助。

最佳答案

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

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

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

关于ios - Firebase:当用户终止应用程序时如何从 Firebase 中清除特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com