如何使用swift获取磁力计数据?

我试图通过使用CoreMotion从我的iphone 6获取磁场数据。

使用以下代码访问原始数据时没有问题:

if available { motionMangager.magnetometerUpdateInterval = updateInterval motionMangager.startMagnetometerUpdatesToQueue(queue, withHandler: { (data, error: NSError!) -> Void in println("x: \(data.magneticField.x), y: \(data.magneticField.y), z: \(data.magneticField.z)") }) } 

但是:我需要使用设备动作实例来获取派生数据。

所以我做了以下事情:

 if motionMangager.deviceMotionAvailable { motionMangager.magnetometerUpdateInterval = updateInterval motionMangager.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrameXArbitraryZVertical, toQueue: queue, withHandler: { (deviceMotion: CMDeviceMotion!, error: NSError!) -> Void in // If no device-motion data is available, the value of this property is nil. if let motion = deviceMotion { println(motion) var accuracy = motion.magneticField.accuracy var x = motion.magneticField.field.x var y = motion.magneticField.field.y var z = motion.magneticField.field.z println("accuracy: \(accuracy.value), x: \(x), y: \(y), z: \(z)") } else { println("Device motion is nil.") } }) } 

这是问题所在:

对于场坐标x,y和z,我总是得零。 准确度也是-1。 根据Apple文档,-1的准确度意味着“CMMagneticFieldCalibrationAccuracyUncalibrated”意味着“该设备没有磁力计”……但不是! 这是iPhone 6 ……

那么我做错了什么? 我尝试了所有四个CMAttitudeReferenceFrame。 我需要帮助。 有任何想法吗?

好的..我解决了。

零的原因是未经校准的磁力计! 但这并不意味着没有像苹果文档中所述的磁力计。 无论如何,我没想到。

我只需要添加指南针校准的function。 这很容易添加:

 motionMangager.showsDeviceMovementDisplay = true 

(参见: https : //developer.apple.com/library/ios/documentation/CoreMotion/Reference/CMMotionManager_Class/ )

所以现在它就像:当我得到零和-1的准确性时,要求校准的警报弹出。 移动后它消失了,我得到了正确的价值观。