加速计和陀螺仪
//返回按钮事件 @IBAction func backButtonClick() { self.navigationController?.popViewControllerAnimated(true) } @IBOutlet var xLabel:UILabel! @IBOutlet var yLabel:UILabel! @IBOutlet var zLabel:UILabel! @IBOutlet var orientationLabel:UILabel! //加速计管理者-所有的操作都会由这个motionManager接管 var motionManager:CMMotionManager! override func viewDidLoad() { super.viewDidLoad() titleLabel.text = titleString //------ CoreMotion 加速计 motionManager = CMMotionManager()//注意CMMotionManager不是单例 motionManager.accelerometerUpdateInterval = 0.1//设置读取时间间隔 if motionManager.accelerometerAvailable//判断是否可以使用加速度计 { //获取主线程并发队列,在主线程里跟新UI motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (var accelerometerData:CMAccelerometerData?, var error:NSError?) -> Void in if error != nil { self.motionManager.stopAccelerometerUpdates()//停止使用加速度计 }else { self.xLabel.text = "x:\(accelerometerData!.acceleration.x)" self.yLabel.text = "Y:\(accelerometerData!.acceleration.y)" self.zLabel.text = "Z:\(accelerometerData!.acceleration.z)" } }) }else { let aler = UIAlertView(title: "您的设备不支持加速计", message: nil, delegate: nil, cancelButtonTitle: "OK") aler.show() } //感知设备方向-开启监听设备方向 UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() //添加通知,监听设备方向改变 NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedRotation", name: UIDeviceOrientationDidChangeNotification, object: nil) //关闭监听设备方向 UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 判断设备方向代理方法 func receivedRotation() { var device = UIDevice.currentDevice() if device.orientation == UIDeviceOrientation.Unknown { orientationLabel.text = "Unknown" } else if device.orientation == UIDeviceOrientation.Portrait { orientationLabel.text = "Portrait" } else if device.orientation == UIDeviceOrientation.PortraitUpsideDown { orientationLabel.text = "PortraitUpsideDown" } else if device.orientation == UIDeviceOrientation.LandscapeLeft { orientationLabel.text = "LandscapeLeft" } else if device.orientation == UIDeviceOrientation.LandscapeRight { orientationLabel.text = "LandscapeRight" }else if device.orientation == UIDeviceOrientation.FaceUp { orientationLabel.text = "FaceUp" } else if device.orientation == UIDeviceOrientation.FaceDown { orientationLabel.text = "FaceDown" } } // MARK: - 摇晃事件 override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) { println("motionBegan")//开始摇晃 } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { println("motionEnded")//摇晃结束 } override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent) { println("motionCancelled")//摇晃被意外终止 }