2016-01-13 83 views
5

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

我已经找到了描述如何在视图控制器中这样做的答案,但是希望在我的应用程序中这样做。

+2

的可能的复制[当有人动摇的iPhone如何检测?(http://stackoverflow.com/questions/150446/how-do-i-detect-当别人摇一摇一个iPhone) – fishinear

回答

7

添加下面的代码片段在AppDelegate

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

雨燕3.0的版本:

override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { 
    if motion == .motionShake { 
     print("Device shaken") 
    } 
} 
+2

这没有奏效,因为应用程序委托不在响应者链中。 – phatmann

+0

不能在swift3中工作 –

+0

@SaRaVaNaNDM,当然它只是测试它,并已经过测试。你有没有得到任何错误?你是如何实现它的? –

6

如果你想在全球范围内检测震动的运动中,一个UIWindow实现UIResponder可以接收震运动事件。您可以添加以下代码段的appdelegate

extension UIWindow { 
    open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { 
     if motion == .motionShake { 
      print("Device shaken") 
     } 
    } 
} 
+0

这对我有用。只要添加它(没有UIWindow扩展),当我将它放入应用程序委托中时不起作用。必须在iOS 10.3/Xcode8.3的func前添加“open”。 –

+0

很奇怪,motionBegan被调用,但motionEnded不会。 – User9527