Skip to content

Update HealthKitReader.swift #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions Sources/Service/HealthKitReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -565,19 +565,20 @@ public class HealthKitReader {
public func anchoredObjectQuery(
type: SampleType,
predicate: NSPredicate? = .allSamples,
anchor: Anchor? = HKQueryAnchor(
fromValue: Int(HKAnchoredObjectQueryNoAnchor)
),
limit: Int = HKObjectQueryNoLimit,
monitorUpdates: Bool = false,
completionHandler: @escaping AnchoredResultsHandler
) throws -> AnchoredObjectQuery {
let _anchor: Anchor? = self.getAnchor(for: type)
guard let sampleType = type.original as? HKSampleType else {
throw HealthKitError.invalidType(
"\(type) can not be represented as HKSampleType"
)
}
let resultsHandler: AnchoredObjectQueryHandler = { (query, data, deletedData, anchor, error) in
if anchor != nil {
self.setAnchor(anchor, for: type)
}
guard
error == nil,
let result = data
Expand Down Expand Up @@ -612,15 +613,44 @@ public class HealthKitReader {
let query = HKAnchoredObjectQuery(
type: sampleType,
predicate: predicate,
anchor: anchor,
anchor: _anchor,
limit: limit,
resultsHandler: resultsHandler
)
if monitorUpdates {
query.updateHandler = resultsHandler
}

return query
}


let userDefaults = UserDefaults.standard

let anchorKeyPrefix = "Anchor_"

func anchorKey(for type: SampleType) -> String {
return anchorKeyPrefix + (type.identifier ?? "")
}

/// Returns the saved anchor used in a long-running anchored object query for a particular sample type.
/// Returns nil if a query has never been run.
func getAnchor(for type: SampleType) -> HKQueryAnchor? {
if let anchorData = userDefaults.object(forKey: anchorKey(for: type)) as? Data {
return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: anchorData)
}

return nil
}

/// Update the saved anchor used in a long-running anchored object query for a particular sample type.
func setAnchor(_ queryAnchor: HKQueryAnchor?, for type: SampleType) {
if let queryAnchor = queryAnchor,
let data = try? NSKeyedArchiver.archivedData(withRootObject: queryAnchor, requiringSecureCoding: true) {
userDefaults.set(data, forKey: anchorKey(for: type))
userDefaults.synchronize()
}
}
/**
Queries sources.
- Parameter type: **SampleType** types
Expand Down