AppDelegate applicationDidEnterBackground 在模拟器上工作但不在设备上工作

AppDelegate applicationDidEnterBackground working on simulator but not Device

我正在尝试跟踪用户在线或离线的时间。我试图通过在打开应用程序时更新解析服务器中的用户对象以及每当使用以下代码关闭应用程序时更新解析服务器中的用户对象来执行此操作。

 func applicationWillEnterForeground(_ application: UIApplication) {

        let username : String? = UserDefaults.standard.string(forKey: "username")
        if username != nil {
            print("online")
            let object = PFUser.current()
            object!["online"] = "yes"
            object?.saveInBackground()

        }

    }

    func applicationDidEnterBackground(_ application: UIApplication) {

        let username : String? = UserDefaults.standard.string(forKey: "username")
        if username != nil {
            print("Offline")
            let object = PFUser.current()
            object!["online"] = "no"
            object?.saveInBackground()

        }
    }

当我在 Mac 上使用模拟器对此进行测试时,它似乎运行良好。但是,当我在实际 iPhone 上对其进行测试时,它会在打开应用程序时更新,但不会在关闭时更新。 (打印总是在设备和模拟器上打印,所以函数被调用)

经过一些研究,我发现我的 info.plist Application does not run in background 中可能需要这个,所以我添加了它并将其设置为否。但是还是不行。

你为什么不使用其他应用程序状态方法,比如 func applicationDidEnterBackground(_ application: UIApplication) {}

记住 applicationWillResignActive(:) 在 applicationDidEnterBackground(:)

之前被调用