有时,当应用程序断开连接时,实现无法工作



当应用程序断开连接时,我想在google fireresore中删除一些数据。但是,下面的代码不能正常工作。

同样,它在模拟器中可以正常工作,但在实际机器上不能。

import Firebase
import FirebaseFirestore
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

let db = Firestore.firestore()
var window: UIWindow?

func sceneDidDisconnect(_ scene: UIScene) {
db.collection("parentCol").document("doc").collection("col_1").document("doc_1").delete()
db.collection("parentCol").document("doc").collection("col_2").document("doc_2").delete() 
db.collection("parentCol").document("doc").delete()
}
}

我的期望


(我正在制作一个游戏应用程序)

  • 主机确定roomId并生成一个房间。
  • 客人通过roomId连接到房间。
  • 当游戏结束或玩家与应用程序断开连接时,不再需要的服务器数据将被删除。
//data structure
col: rooms
|
|- doc: 1234 (roomId)
|     |
|     |- col: members
|           |
|           |- doc: name ( here I store an array of String)
|                 |- 1: Tom
|                 |- 2: Ares
|                 |- 3: Michael
|
|- doc: abc (roomId) 

What I tried


在模拟器中工作得很好。但是,当我在实际设备上尝试时,它不能正常工作。

以下代码中只删除了doc_1

func sceneDidDisconnect(_ scene: UIScene) {
db.collection("parentCol").document("doc").collection("col_1").document("doc_1").delete()
db.collection("parentCol").document("doc").delete()
}

以下代码中只删除了doc

func sceneDidDisconnect(_ scene: UIScene) {
db.collection("parentCol").document("doc").delete()
}

当执行以下代码时,不删除任何内容。↓

func sceneDidDisconnect(_ scene: UIScene) {
db.collection("parentCol").document("doc").collection("col_1").document("doc_1").delete()
db.collection("parentCol").document("doc").collection("col_2").document("doc_2").delete() 
db.collection("parentCol").document("doc").delete()
}

我知道一个应用程序断开连接后,它只会运行几秒钟。但这应该是足够的时间来删除数据。

如果你有任何解决办法,请告诉我。

我的母语不是英语,所以很抱歉,如果你很难阅读。

我认为模拟器上发生的事情(即sceneDidDisconnect延迟了几秒钟)是相当异常的,而您在设备上看到的行为是正确的(即sceneDidDisconnect几乎是瞬时的)。

我建议你重新阅读管理你的应用程序的生命周期。它声明场景断开是为了清理,而任何数据操作都应该在之前完成,当应用程序即将离开前景活动状态时:

  • 在离开前台活动状态时,保存数据并安静应用程序的行为。参见准备UI在后台运行。
  • 进入后台状态后,完成关键任务,释放尽可能多的内存,并准备应用程序快照。参见准备UI在后台运行。
  • 场景断开时,清理与场景相关的所有共享资源。

所以使用sceneWillResignActive(_:)来执行删除。此外:正如Apple声明-

不要依赖于特定的应用程序转换来保存应用程序的所有关键数据。

如果你能在其他的应用事件上做这些删除,那就那样做,并且只使用应用事件作为备份。还要确保你的应用程序处理的情况下,数据可能仍然存在的应用程序的下一次调用(因为如果应用程序被杀死在一些更残酷的方式可能永远不允许任何关闭功能运行)。

最新更新