I am using Swift to write an iPhone App which tracks an aircraft taking off and landing (as indicated by a change in air pressure).
For this I need to measure the iPhone's air pressure whilst it is running in the background. I need to measure the pressure at intervals of at least once every minute for a period of an hour or 2. I have read the Apple Developer Background Execution guide, but I don't think any of the background modes are relevant; for example, a finite-length task does not last long enough and a fetch task seems to be too infrequent.
My current code to obtain air pressure is as follows:
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
}
}
I have changed the QoS
of this operationQueue
to .background
, but as I understand it, this just makes this a lower priority to get updated & has nothing to do with running as a background execution (correct?).
Is there anything else I can try to periodically obtain the air pressure under a background execution? I can't imagine that obtaining the air pressure every minute or so would use a huge amount of power, so I would hope that it would be possible.
Any help available would be much appreciated!
Thanks,
You are correct, the
cos
attribute of anOperationQueue
only changes its priority, setting it tobackground
won't make your app run in the background.As for getting altitude data in the background, you should use the
CoreLocation
library rather than theCoreMotion
and use background location updates.You have to make your class conform to
CLLocationManagerDelegate
, start the location updates and then implement the following delegate method:Behind the scenes, the system is most probably using
CMAltimeter
to get the altitude data, but there is no API to get it in the background, hence you have to useCoreLocation
.