Skip to content

Instantly share code, notes, and snippets.

@nderkach
Last active September 14, 2018 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nderkach/2892594e5162857e7a008defeeb6f53e to your computer and use it in GitHub Desktop.
Save nderkach/2892594e5162857e7a008defeeb6f53e to your computer and use it in GitHub Desktop.
private var myAnchor: HKQueryAnchor?
/// Sets up the observer queries for background health data delivery.
///
/// - parameter types: Set of `HKObjectType` to observe changes to.
private func setUpBackgroundDeliveryForDataTypes(types: Set<HKObjectType>) {
for type in types {
guard let sampleType = type as? HKSampleType else { print("ERROR: \(type) is not an HKSampleType"); continue }
if let anchorData = UserDefaults.standard.object(forKey: "anchor") as? Data {
myAnchor = NSKeyedUnarchiver.unarchiveObject(with: anchorData) as? HKQueryAnchor
}
let query = HKAnchoredObjectQuery(type: sampleType,
predicate: nil,
anchor: myAnchor,
limit: HKObjectQueryNoLimit) { [weak self] (_, samplesOrNil, _, newAnchor, _) in
debugPrint("observer query update handler called for type \(sampleType)")
guard let samples = samplesOrNil else {
// Handle the error here.
return
}
guard samples.last != nil else {
return
}
guard let strongSelf = self else { return }
strongSelf.myAnchor = newAnchor
if let newAnchor = newAnchor {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: newAnchor), forKey: "anchor")
}
}
// Optionally, add an update handler.
query.updateHandler = { [weak self] (query, samplesOrNil, deletedObjectsOrNil, newAnchor, errorOrNil) in
guard let samples = samplesOrNil else {
// Handle the error here.
fatalError("*** An error occurred during an update: \(errorOrNil!.localizedDescription) ***")
}
print(samples.count)
guard let lastSample = samples.last else {
return
}
guard let strongSelf = self else { return }
strongSelf.myAnchor = newAnchor
if let newAnchor = newAnchor {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: newAnchor), forKey: "anchor")
}
strongSelf.handleSample(lastSample)
}
healthStore.execute(query)
healthStore.enableBackgroundDelivery(for: type, frequency: .immediate) { (success: Bool, error: Error?) in
debugPrint("enableBackgroundDeliveryForType handler called for \(type) - success: \(success), error: \(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment