簡體   English   中英

如何使用swift獲取磁力計數據?

[英]How to get magnetometer data using 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。 我需要幫助。 有任何想法嗎?

好的..我解決了。

零的原因是未經校准的磁力計! 但這並不意味着沒有像蘋果文檔中所述的磁力計。 無論如何,我沒想到。

我只需要添加指南針校准的功能。 這很容易添加:

motionMangager.showsDeviceMovementDisplay = true

(參見: https//developer.apple.com/library/ios/documentation/CoreMotion/Reference/CMMotionManager_Class/

所以現在它就像:當我得到零和-1的准確性時,要求校准的警報彈出。 移動后它消失了,我得到了正確的價值觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM