I would like to use the shake function to turn off an alarm clock, which would cause the user to shake the phone for 30 seconds. Is there a way to test for how long the user has been shaking the device as well as how would I set up the shake function?
I only understand swift code by the way.
You can do it like this
var timer = Timer()
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken, shake timer started")
timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(turnOffAlarm), userInfo: nil, repeats: true)
}
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shake stop, shake timer stopeed")
timer.invalidate()
}
}
@objc func turnOffAlarm() {
print("Alarm off")
timer.invalidate()
}
When the user starts shaking the phone you start your timer with a 30 second interval, if the user stop shaking you will call invalidate otherwise after 30 seconds you will call turnOffAlarm and invaldiate the timer.