Home > OS >  Firestore call doesn't execute completely after user terminates the app
Firestore call doesn't execute completely after user terminates the app

Time:12-07

I need a firestore function to execute when the user terminates the app. Specifically, I need to delete a document in firestore. I used the applicationWillTerminate in the AppDelegate for that.

This is the code:

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")
            }
        }
        
    }

Terminal successfully prints "App terminated" meaning that the function is called when the user terminates the app. However, the Firestore call doesn't completely execute, which I would believe is due to the short time limit the applicationWillTerminate has. Is there any way I can get the Firestore document to delete/the call to execute completely?

CodePudding user response:

I have solved the problem by implementing the code in the sceneDidDisconncet in the SceneDelegate instead of the applicationWillTerminate. This works well for what I was trying to achieve and the Firestore document is deleted when the user kills/terminates the app. This is the code snippet (in the 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).
}
  • Related