I am trying to keep track of when the user is online or offline. I am attempting to do this by updating the user object in parse server whenever the app is opened, and whenever the app is closed with the following code.
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()
}
}
When I test this out with the simulator on Mac, it seems to work perfectly. However, when I test it out on my actual iPhone it updates when the app is opened but not when it is closed. (the print is always printing both on device and simulator so the function is getting called)
After doing some research I have found that I may need this in my info.plist Application does not run in background
So i have added that and set it to no. However it is still not working.
Why don't you use another application state method, like func applicationDidEnterBackground(_ application: UIApplication) {}
Remember that applicationWillResignActive(:) is called before than applicationDidEnterBackground(:)