0

我正在使用 Swift 编写一个跟踪飞机起飞和着陆的 iPhone 应用程序(如气压变化所示)。

为此,我需要测量 iPhone 在后台运行时的气压。我需要至少每隔一分钟测量一次压力,持续一到两个小时。我已经阅读了Apple Developer Background Execution guide,但我认为任何后台模式都不相关;例如,有限长度的任务不会持续足够长的时间,而 fetch 任务似乎太少见了。

我目前获取气压的代码如下:

let opQueue = OperationQueue.current!
opQueue.qualityOfService = .background
altimeter.startRelativeAltitudeUpdates(to: opQueue) { (data, error) in
      print ("Pressure returned")
      //If pressure returned from iPhone correctly:
      if let data = data {
          self.localPressure = convertPressure(data.pressure.doubleValue, fromUnit: .kPa, toUnit: .hPa) //In hPa
      }
}

我已将其更改QoS为,但operationQueue.background我了解,这只会降低更新的优先级,并且与作为后台执行运行无关(正确吗?)。

还有什么我可以尝试在后台执行下定期获取气压吗?我无法想象每分钟左右获得气压会消耗大量电力,所以我希望它是可能的。

任何可用的帮助将不胜感激!

谢谢,

4

1 回答 1

0

你是对cos的,一个属性OperationQueue只会改变它的优先级,设置它background不会让你的应用程序在后台运行。

至于在后台获取高度数据,您应该使用CoreLocation库而不是CoreMotion使用后台位置更新。

您必须使您的类符合CLLocationManagerDelegate,开始位置更新,然后实现以下委托方法:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let currentLocation = locations.last else { return }
    let altitude = currentLocation.altitude
    //use altitude to check whether plane is taking off or landing
}

在幕后,系统很可能是CMAltimeter用来获取海拔数据的,但没有在后台获取它的 API,因此您必须使用CoreLocation.

于 2017-08-11T13:17:54.957 回答