I need to do something in applicationDidEnterBackground
. But I need to differentiate which user action causes the \"enter background\": screen lock or home butt
This solution was taken from this answer and worked for me. It is a bit hacky but it makes it easier to be accepted on the appstore because it doesn't use com.apple.springboard.lockcomplete or com.apple.springboard.lockstate.
The following code goes into your AppDelegate:
func applicationDidEnterBackground(_ application: UIApplication) {
if (DidUserPressLockButton()) {
print("User pressed lock button")
} else {
print("user pressed home button")
}
}
private func DidUserPressLockButton() -> Bool {
let oldBrightness = UIScreen.main.brightness
UIScreen.main.brightness = oldBrightness + (oldBrightness <= 0.01 ? (0.01) : (-0.01))
return oldBrightness != UIScreen.main.brightness
}
The idea is to try changing the brightness of the screen after the application went to background and to check if this change was successful.
Disclaimer: it doesn't work on the simulator and you will have to test it on a real device.