在AppDelegate中检测抖动

Lir*_*hen 8 shake ios appdelegate swift swift3

如何在Swift中的AppDelegate(整个应用程序)中检测到设备震动?

我找到了解释如何在视图控制器中执行此操作的答案,但希望在我的应用程序中执行此操作.

jk2*_*k2K 18

如果要全局检测摇动,UIWindow会实现可以接收摇动动作事件的UIResponder.您可以将以下代码段添加到AppDelegate

extension UIWindow {
    open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            print("Device shaken")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在尝试了许多其他解决方案后,这是唯一对我有用的解决方案。此外,我了解到我可以覆盖扩展中的函数。惊人的! (2认同)

Ras*_*n L 7

在您的AppDelegate:中添加以下代码段:

override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake {
        print("Device shaken")
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.0版本:

override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        print("Device shaken")
    }
}
Run Code Online (Sandbox Code Playgroud)

至于后来的版本,这似乎不再起作用了.您需要在视图控制器中添加上述代码

  • 这不起作用,因为app委托不在响应者链中. (3认同)