繁体   English   中英

用户终止应用程序后,Firestore 调用未完全执行

[英]Firestore call doesn't execute completely after user terminates the app

当用户终止应用程序时,我需要一个 firestore function 来执行。 具体来说,我需要删除 firestore 中的一个文档。 为此,我在 AppDelegate 中使用了 applicationWillTerminate。

这是代码:

func applicationWillTerminate(_ application: UIApplication) {
        
        print("App terminated")
        
        guard let email = UserDefaults.standard.value(forKey: "email") as? String else {
            return
        }
        let safeEmail = DatabaseManager.safeEmail(emailAddress: email)
        Firestore.firestore().collection("LocationsList").document(safeEmail).delete() { err in
            if let err = err {
                print("Error removing document: \(err)")
            }
            else {
                print("Document removed")
            }
        }
        
    }

终端成功打印“App terminated”,这意味着 function 在用户终止应用程序时被调用。 但是,Firestore 调用并未完全执行,我认为这是由于 applicationWillTerminate 的时间限制较短所致。 有什么办法可以让 Firestore 文档删除/调用完全执行?

我通过在 SceneDelegate 而不是 applicationWillTerminate 中实现 sceneDidDisconncet 中的代码解决了这个问题。 这对我试图实现的目标很有效,当用户终止/终止应用程序时,Firestore 文档将被删除。 这是代码片段(在 SceneDelegate 中):

func sceneDidDisconnect(_ scene: UIScene) {
    //print("inactive")
    guard let email = UserDefaults.standard.value(forKey: "email") as? String else {
                return
            }
            let safeEmail = DatabaseManager.safeEmail(emailAddress: email)
            Firestore.firestore().collection("LocationsList").document(safeEmail).delete() { err in
                if let err = err {
                    print("Error removing document: \(err)")
                }
                else {
                    print("Document removed")
                }
            }
    // Called as the scene is being released by the system.
    // This occurs shortly after the scene enters the background, or when its session is discarded.
    // Release any resources associated with this scene that can be re-created the next time the scene connects.
    // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM