(1)代码实现如下:
import UIKit import CoreMotion class ViewController: UIViewController { var cmm:CMMotionManager! override func viewDidLoad() { super.viewDidLoad() cmm = CMMotionManager() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) cmm.accelerometerUpdateInterval = 1 //1s获取一次加速度数据; if(cmm.accelerometerAvailable){ cmm.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: { (data:CMAccelerometerData!,err:NSError!) in println(data) }) }else{//模拟器中不能获取到传感器数据; println("加速度传感器不可用") } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if(cmm.accelerometerActive){ cmm.stopAccelerometerUpdates() } } }