使用CoreLocation以指定的时间间隔检索后台的CoreMotion数据

时间:2017-05-24 16:10:36

标签: ios swift core-location background-process core-motion

我有一个汽车应用需要在前景和后台以指定的时间间隔(0.5秒)跟踪CoreMotion和CoreLocation数据。用户控制跟踪的开始和停止,因此我们不必担心电池寿命问题。这就是我目前所拥有的:

var locationManager:CLLocationManager?
var motionManager:CMMotionManager?

override init() {
    super.init()
    locationManager = CLLocationManager()
    motionManager = CMMotionManager()
    locationManager?.delegate = self
    locationManager?.allowsBackgroundLocationUpdates = true
}

//Call this to start tracking
func startTracking() {
    motionManager?.startDeviceMotionUpdates()
    locationManager?.startUpdatingLocation()
}
//Call this to stop tracking
func stopTracking(){
    locationManager?.stopUpdatingLocation()
    motionManager?.stopDeviceMotionUpdates()
}

//Using CoreLocation delegate method to retrieve both motion and location data.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last{
        if let data = motionManager?.deviceMotion {
            print("Data: \(data) Location:\(location)")
        }
    }
}

我现在遇到的这个问题是我无法控制位置更新的频繁发生以获取我的CoreMotion数据。我需要在后台每隔0.5秒跟踪CoreMotion数据,CoreLocation数据不必频繁。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

对于迟到的回复感到抱歉,但要设置更新间隔,您应该写一下:

motionManager.deviceMotionUpdateInterval = 0.5