-
-
Save dilumdesilva/50c11ff5e1afec3f24ca8a5089bab97e to your computer and use it in GitHub Desktop.
Check devices motions -> pitch, roll and yaw SWIFT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreMotion // Import CoreMotion (header) | |
// Class vars | |
var pitch = 0.0 | |
var attitude: CMAttitude? | |
var roll = 0.0 | |
var yaw = 0.0 | |
let motionManager = CMMotionManager() // Create motionManager instance | |
// Func to get degrees from a double - use if you want to do something like if your user lifts up device (see below) | |
func degrees(radians:Double) -> Double { | |
return 180 / M_PI * radians | |
} | |
func checkPitch(deviceMotion:CMDeviceMotion) { | |
attitude = deviceMotion.attitude | |
roll = degrees(attitude!.roll) | |
yaw = degrees(attitude!.yaw) | |
pitch = degrees(attitude!.pitch) | |
print("Roll: \(roll)n/Pitch: \(pitch)n/Yaw: \(yaw)") | |
// Check if device has been raised vertically (you can also check for any or a combination of the attitudes) | |
if pitch >= 85.0 { | |
motionManager.stopDeviceMotionUpdates() | |
print("Device is nearly vertical. Yay!") | |
} | |
} | |
func updateDeviceMotions() { | |
motionManager.deviceMotionUpdateInterval = 0.05 // Change to whatever suits your app - milli-seconds | |
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: { | |
(deviceMotion, error) -> Void in | |
if(error == nil) { | |
self.checkPitch(deviceMotion!) | |
} else { | |
// Do something if theres an error | |
} | |
}) | |
} | |
// Call this when you want to start the function | |
motionManager.startDeviceMotionUpdates() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment