我正在使用Core Motion,我在“解包可选值时意外发现nil”,但只有一半的时间加载应用程序。如何更正以下代码,以便稳定?
import UIKit
import CoreMotion
class ViewController: UIViewController {
var currentMaxRotX: Double = 0.0
var currentMaxRotY: Double = 0.0
var currentMaxRotZ: Double = 0.0
let motionManager = CMMotionManager()
@IBOutlet var RollLabel: UILabel!
@IBOutlet var PitchLabel: UILabel!
@IBOutlet var YawLabel: UILabel!
@IBOutlet var rotX: UILabel!
@IBOutlet var rotY: UILabel!
@IBOutlet var rotZ: UILabel!
@IBOutlet var maxRotX: UILabel!
@IBOutlet var maxRotY: UILabel!
@IBOutlet var maxRotZ: UILabel!
@IBOutlet var readOutLabel: UILabel!
override func viewDidLoad() {
if motionManager.gyroAvailable {
motionManager.startGyroUpdates()
motionManager.deviceMotionUpdateInterval = 0.2
motionManager.startDeviceMotionUpdates()
motionManager.gyroUpdateInterval = 0.2
motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue()) {
[weak self] (gyroData: CMGyroData!, error: NSError!) in
if self?.outputRotationData(gyroData.rotationRate) != nil {
self?.outputRotationData(gyroData.rotationRate)
if error != nil {
println("\(error)")
}
}
}
} else {
println("gyro not avail")
}
super.viewDidLoad()
}
// radians to degrees
func radians(fromDegrees degrees: Double) -> Double {
return 180 * degrees / M_PI
}
func outputRotationData(rotation:CMRotationRate)
{
rotX.text = NSString(format:"Rotation X: %.4f",rotation.x) as String
if fabs(rotation.x) > fabs(currentMaxRotX)
{
currentMaxRotX = rotation.x
}
rotY.text = NSString(format:"Rotation Y: %.4f", rotation.y) as String
if fabs(rotation.y) > fabs(currentMaxRotY)
{
currentMaxRotY = rotation.y
}
rotZ.text = NSString(format:"Rotation Z:%.4f", rotation.z) as String
if fabs(rotation.z) > fabs(currentMaxRotZ)
{
currentMaxRotZ = rotation.z
}
maxRotX.text = NSString(format:"Max rotation X: %.4f", currentMaxRotX) as String
maxRotY.text = NSString(format:"Max rotation Y:%.4f", currentMaxRotY) as String
maxRotZ.text = NSString(format:"Max rotation Z:%.4f", currentMaxRotZ) as String
var attitude = CMAttitude()
var motion = CMDeviceMotion()
motion = motionManager.deviceMotion
attitude = motion.attitude
YawLabel.text = NSString (format: "Yaw: %.2f", attitude.yaw) as String
PitchLabel.text = NSString (format: "Pitch: %.2f", attitude.pitch) as String
RollLabel.text = NSString (format: "Roll: %.2f", attitude.roll) as String
if NSString(string: RollLabel.text!).doubleValue <= -1.6 && NSString(string: RollLabel.text!).doubleValue >= -1.2 {
readOutLabel.text = ""
}
else{
readOutLabel.text = ""
}
}
}
答案 0 :(得分:0)
我明白了:
var attitude = CMAttitude()
var motion = CMDeviceMotion()
if motionManager.deviceMotion != nil{
motion = motionManager.deviceMotion
attitude = motion.attitude
YawLabel.text = NSString (format: "Yaw: %.2f", attitude.yaw) as String
PitchLabel.text = NSString (format: "Pitch: %.2f", attitude.pitch) as String
RollLabel.text = NSString (format: "Roll: %.2f", attitude.roll) as String
}