1、加速计和陀螺仪
导入CoreMotion.framework框架。
@IBOutlet var xLabel:UILabel! @IBOutlet var yLabel:UILabel! @IBOutlet var zLabel:UILabel! @IBOutlet var orientationLabel:UILabel! //加速计管理者-所有的操作都会由这个motionManager接管 var motionManager:CMMotionManager!
//------ CoreMotion 加速计 motionManager = CMMotionManager()//注意CMMotionManager不是单例 motionManager.accelerometerUpdateInterval = 0.1//设置读取时间间隔 if motionManager.accelerometerAvailable//判断是否可以使用加速度计 { //获取主线程并发队列,在主线程里跟新UI motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (let accelerometerData:CMAccelerometerData?, let 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() }
2、判断设备方向
//感知设备方向-开启监听设备方向 UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() //添加通知,监听设备方向改变 NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedRotation", name: UIDeviceOrientationDidChangeNotification, object: nil) //关闭监听设备方向 UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()
// MARK: - 判断设备方向代理方法 func receivedRotation() { let 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" } }
3、摇晃事件
// MARK: - 摇晃事件 override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionBegan")//开始摇晃 } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionEnded")//摇晃结束 } override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionCancelled")//摇晃被意外终止 }