Differentiate between screen lock and home button press on iOS7

前端 未结 3 1852
生来不讨喜
生来不讨喜 2020-12-03 11:24

I need to do something in applicationDidEnterBackground. But I need to differentiate which user action causes the \"enter background\": screen lock or home butt

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 12:03

    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.

提交回复
热议问题