Core Motion

Core Motion是苹果提供的一个框架,用来读取设备中的传感器数据。

加速计等

使用CMMotionManager类来管理这些硬件传回来的数据。

var motionManager = CMMotionManager()
self.motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) { (motion:CMDeviceMotion?, error:NSError?) -> Void in
    let xString = NSString(format: "%.1f", (motion?.userAcceleration.x)!)
    let yString = NSString(format: "%.1f", (motion?.userAcceleration.y)!)
    let zString = NSString(format: "%.1f", (motion?.userAcceleration.z)!)
    self.XLabel.text = xString as String
    self.YLabel.text = yString as String
    self.ZLabel.text = zString as String
    let pitchDegress = (motion?.attitude.pitch)! * 180 / M_PI
    let rollDegress = (motion?.attitude.roll)! * 180 / M_PI
    let yawDegress = (motion?.attitude.yaw)! * 180 / M_PI
    let pitchString = NSString(format: "%.1f", pitchDegress)
    let rollString = NSString(format: "%.1f", rollDegress)
    let yawString = NSString(format: "%.1f", yawDegress)
    self.pitchLabel.text = pitchString as String
    self.rollLabel.text = rollString as String
    self.yawLabel.text = yawString as String
}

高度计

let altimer = CMAltimeter()
if CMAltimeter.isRelativeAltitudeAvailable() {
    var currentAltitude: Float =  0.0
    altimer.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data:CMAltitudeData?, error:NSError?) -> Void in currentAltitude += Float((data?.relativeAltitude)!) self.heightLabel.text = "\(currentAltitude)" }) }

计步器

let pedometer = CMPedometer()
if CMPedometer.isStepCountingAvailable() {
    let calender = NSCalendar.currentCalendar()
    let now = NSDate()
    let weekAgo = calender.dateByAddingUnit(NSCalendarUnit.Day, value: -6, toDate: now, options: NSCalendarOptions())
    pedometer.queryPedometerDataFromDate(weekAgo!, toDate: now, withHandler: { (data:CMPedometerData?, error:NSError?) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in if let stepData = data{ self.weekLabel.text = "\(stepData.numberOfSteps)" } }) }) //这两个API不能同时使用 // pedometer.startPedometerUpdatesFromDate(now, withHandler: { (data:CMPedometerData?, error:NSError?) -> Void in // if let stepData = data{ // self.nowSteps.text = "\(stepData.numberOfSteps)" // } // }) }

你可能感兴趣的:(ios,osx,CoreMotion)