Swift - Shake Motion
Aus Wikizone
Links[Bearbeiten]
Swift Swift - Snippets
Motion Detection - Shake[Bearbeiten]
Quelle OpenAI
How can i react to a shake in swift
To react to a shake in Swift, you can use the MotionManager class to detect when the device is shaken. Here is an example of how to use MotionManager to detect a shake and perform an action:
import CoreMotion
class ViewController: UIViewController {
let motionManager = CMMotionManager()
override func viewDidLoad() {
super.viewDidLoad()
// Start detecting shakes
motionManager.startAccelerometerUpdates(to: .main) { (data, error) in
if let data = data {
// Use the accelerometer data to detect a shake
if self.isShaken(data: data) {
// Perform an action when the device is shaken
print("Device was shaken")
}
}
}
}
func isShaken(data: CMAccelerometerData) -> Bool {
// Set the threshold for detecting a shake
let threshold = 1.5
let x = data.acceleration.x
let y = data.acceleration.y
let z = data.acceleration.z
// Check if the acceleration in any direction exceeds the threshold
if x > threshold || y > threshold || z > threshold {
return true
}
return false
}
}
This code sets up the MotionManager to start receiving accelerometer updates and checks the accelerometer data for a shake. You can adjust the threshold value to change how sensitive the shake detection is. When a shake is detected, the isShaken function returns true, and you can perform any action you want in response to the shake.
Keep in mind that you will need to import the CoreMotion framework and add the CoreMotion framework to your project in order to use CMMotionManager and CMAccelerometerData.