采用CoreMotion.framework加速度框架
代码方面主要分两块,要有一个加速度的核心类,负责获取到加速度,一个视图控制类,视图控制类可自由选择,在需要的时候调用加速度核心类。
一:加速度核心类:
首先需要创建一个加速度核心类MotionClass,导入CoreMotion
核心类的创建思路是:
1.需要创建一个单例,获取到加速度cmmotionmanager实例。
2.类中需要两个方法,一个Start获取加速度,一个Stop停止获取加速度
3.需要创建一个协议方法,用于传导获取到的加速度变量
类代码如下
//
// motion.swift
// testacceleration
//
// Created by X-DL on 15/4/11.
// copyright (c) 2015年 dl. All rights reserved.
//
import UIKit
import CoreMotion
protocol MotionDelegate:NSObjectProtocol{
func updateXY(X:Double,Y:Double,Z:Double)
}
class MotionClass:UIView{
/// 创建协议实例
weak var delegate : MotionDelegate?
/// 创建加速度单例
class var shareMotion: cmmotionmanager {
struct MotionStruct{
static var motionManager:cmmotionmanager?
static var token:dispatch_once_t = 0
}
dispatch_once(&MotionStruct.token) {
if MotionStruct.motionManager == nil
{
MotionStruct.motionManager = cmmotionmanager()
}
}
return MotionStruct.motionManager!
}
/**
开始加速度检测方法
*/
func startMotion(){
let motion = MotionClass.shareMotion
if motion.gyroAvailable {
motion.accelerometerUpdateInterval = NSTimeInterval(2)
motion.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(),withHandler: {
(data,error) in
let x = data.acceleration.x
let y = data.acceleration.y
let z = data.acceleration.z
//调用协议,传入参数
self.delegate?.updateXY(x,Y:y,Z:z)
})
}else{
println("motino is false")
}
}
/**
停止加速度检测
*/
func stopMotion(){
MotionClass.shareMotion.stopAccelerometerUpdates()
}
} 这样即是加速度核心类的基本框架,而后在VC类中实现协议方法,设置MotionClass的delegate为self。然后调用相应的start或stop方法即可