Last active
September 14, 2018 17:43
-
-
Save nderkach/2892594e5162857e7a008defeeb6f53e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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