Skip to content

Instantly share code, notes, and snippets.

@vichudson1
Last active May 29, 2018 02:40
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 vichudson1/5af2036966cfd0dabba8b0f469e8e568 to your computer and use it in GitHub Desktop.
Save vichudson1/5af2036966cfd0dabba8b0f469e8e568 to your computer and use it in GitHub Desktop.
public typealias QuantitySampleQueryResultsHandler = (_ query: HKSampleQuery, _ samples: [HKQuantitySample]) -> Void
public typealias CategorySampleQueryResultsHandler = (_ query: HKSampleQuery, _ samples: [HKCategorySample]) -> Void
func quantitySampleQuery(startDate: Date,
endDate: Date?,
dateOptions: HKQueryOptions = [.strictStartDate, .strictEndDate],
sampleType: HKQuantityType,
resultsLimit: Int = Int(HKObjectQueryNoLimit),
resultsHandler: @escaping QuantitySampleQueryResultsHandler) -> HKSampleQuery {
// Build sort descriptor to return the samples in descending order
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
// Limit the number of samples returned by the query to the number requested
let limit = resultsLimit
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: dateOptions)
// Build the query
let query = HKSampleQuery(sampleType: sampleType, predicate: datePredicate, limit: limit, sortDescriptors: [sortDescriptor]) {
(sampleQuery, results, error ) -> Void in
guard let samples = results as? [HKQuantitySample] , error == nil else {
resultsHandler(sampleQuery, [])
guard let queryError = error else { return }
print("\(queryError.localizedDescription)")
return
}
resultsHandler(sampleQuery, samples)
}
return query
}
func categorySampleQuery(startDate: Date,
endDate: Date,
sampleType: HKCategoryType,
resultsLimit: Int = Int(HKObjectQueryNoLimit),
resultsHandler: @escaping CategorySampleQueryResultsHandler) -> HKSampleQuery {
// Build sort descriptor to return the samples in descending order
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
// Limit the number of samples returned by the query to the number requested
let limit = resultsLimit
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.strictStartDate, .strictEndDate])
// Build the query
let query = HKSampleQuery(sampleType: sampleType, predicate: datePredicate, limit: limit, sortDescriptors: [sortDescriptor]) {
(sampleQuery, results, error ) -> Void in
guard let samples = results as? [HKCategorySample] , error == nil else {
resultsHandler(sampleQuery, [])
guard let queryError = error else { return }
print("\(queryError.localizedDescription)")
return
}
resultsHandler(sampleQuery, samples)
}
return query
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment