Get sleep hours using HealthKit - ios

I am trying to get sleep hours through HealthKit for particular date.

I have google it but did’t find any specific solution.

 I have also tried to use below code but it did’t work well.

func getSleepHours() {
if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let startDate = formatter.date(from: "2017/12/02 22:00")
let endDate = formatter.date(from: "2017/12/03 07:31")
// let startDate = Date().yesterday
// let endDate = Date()
//let starTDate = Date)
let predciate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate)
// let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, startDate: endDate, options: .None)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(sampleType: sleepType, predicate: predciate, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if let result = tmpResult {
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "InBed" : "Asleep"
print("sleep: \(sample.startDate) \(sample.endDate) - source: \(sample.source.name) - value: \(value)")
// let seconds = endDate.timeIntervalSinceDate(sample.startDate)
let seconds = sample.startDate.timeIntervalSince(sample.endDate)
let minutes = seconds/60
let hours = minutes/60
print(seconds)
print(minutes)
print(hours)
}
}
}else{
print(error?.localizedDescription)
}
}
healthStore.execute(query)
}
}

Related

How to obtain Health data from the last 7 days

I'm trying to obtain the steps from the last 7 days, but I could not find how to do it. What i would like to receive is an array of 7 elements in which every element is a Day with it respectives total steps. I currently have this code, which obtains today's steps:
//Gets the steps
func getTodaysSteps(completion: #escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
guard let result = result, let sum = result.sumQuantity() else {
print("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
completion(0.0)
return
}
DispatchQueue.main.async {
completion(sum.doubleValue(for: HKUnit.count()))
}
}
healthKitStore.execute(query)
}
And I call the function like this:
getTodaysSteps { (steps) in
self.stepsNumber = Int(steps)
}
Try using HKStatisticsCollectionQuery, which will do the date math for you and bucket the results automatically. Here's an example that should provide the step counts for the last 7 days:
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)
let query = HKStatisticsCollectionQuery.init(quantityType: stepsQuantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: startOfSevenDaysAgo,
intervalComponents: DateComponents(day: 1))
query.initialResultsHandler = { query, results, error in
guard let statsCollection = results else {
// Perform proper error handling here...
}
statsCollection.enumerateStatistics(from: startOfSevenDaysAgo, to: now) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let stepValue = quantity.doubleValueForUnit(HKUnit.countUnit())
// ...
}
}
}
There's even more simpler solution here.
func getTotalSteps(forPast days: Int, completion: #escaping (Double) -> Void) {
// Getting quantityType as stepCount
guard let stepsQuantityType = HKObjectType.quantityType(forIdentifier: .stepCount) else {
print("*** Unable to create a step count type ***")
return
}
let now = Date()
let startDate = Calendar.current.date(byAdding: DateComponents(day: -days), to: now)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
execute(query)
}
Now to call just use the following code:
HKHealthStore().getTotalSteps(forPast: 30) { totalSteps in
print(totalSteps)
}
The only change you have to implement is to change the Date object you supply as the startWith parameter to your HKStatisticsQuery. You can create a Date object representing the start of the day 7 days ago by first going back exactly 7 days in time using Calendar.date(byAdding:,to:), then calling startOfDay(for:) on that object.
let now = Date()
let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)

Getting users data in week, month & year format from healthkit in swift

I need a little help with the implementation of HealthKit in my app. I am working with Swift 4 Xcode 9. I am using the following code to get the users step count for particular day:
func getTodaysSteps(completion: #escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
var resultCount = 0.0
guard let result = result else {
// log.error("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
completion(resultCount)
return
}
if let sum = result.sumQuantity() {
resultCount = sum.doubleValue(for: HKUnit.count())
}
DispatchQueue.main.async {
completion(resultCount)
}
}
healthStore.execute(query)
}
Now I want to get the users step count and calories for each day of an entire month. In other words I want to get users past step count in the week, month and year format. Can anyone please help me with the same ?
your just need to set from date (in your case it could be aWeekAgo, aMothAgo, aYearAgo) and toDate is Current Date
let sevneDaysAgo = NSCalendar.current.date(byAdding: .day, value: -7, to: Date())
let currentDate = Date.init()
PedometerManager.shared.getPedometerDataFromDate(fromDate: sevneDaysAgo, toDate: currentDate) { [weak self] (data, error, errorMsg) in
if(error == nil && data != nil) {
if let count = data?.numberOfSteps {
}
if let distance = data?.distance {
let roundDis = round(distance.doubleValue)
let dis = String.init(format: "%.3f",roundDis)
}
if let pace = data?.currentPace {
}
if let cadence = data?.currentCadence {
}
if let ascend = data!.floorsAscended {
}
if let desc = data!.floorsDescended {
}
if let activity = self?.activityName {
}
}
}
you have to use CMPedometer class

App crashes when calling HKHealthStore's execute method on HKStatisticsCollectionQuery

I'm trying to retrieve the steps data from Health Kit and get an update everytime this data changes.
But when the HKHealthStore calls its execute method on the query, the app crash:
And I have no idea why. Any help is welcome.
Here is my code:
func sretrieveRealTimeSteps(completion: #escaping (Int) -> Void) {
let calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())
anchorComponents.hour = 0
guard let anchorDate = calendar.date(from: anchorComponents) else { completion(0); return }
guard let quantityType = HKObjectType.quantityType(forIdentifier: .stepCount) else { completion(0); return }
let realTimeQuery = HKStatisticsCollectionQuery(quantityType: quantityType,
quantitySamplePredicate: nil,
options: .cumulativeSum,
anchorDate: anchorDate,
intervalComponents: interval)
realTimeQuery.statisticsUpdateHandler = { query, statistics, results, error in
guard let statsCollection = results else {
completion(0)
return
}
statsCollection.enumerateStatistics(from: Date(), to: Date()) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let value = quantity.doubleValue(for: HKUnit.count())
completion(Int(value))
} else {
completion(0)
}
}
}
healthKitStore.execute(realTimeQuery)
}
Also, when I used a one time query there is no problem:
query.initialResultsHandler = { query, results, error in
guard let statsCollection = results else {
NotificationView.showHealthKitRetrieveInfoFailedNotification()
completion(nil, error)
return
}
var values = [Int]()
let endDate = Date()
let startDate = calendar.date(byAdding: .day, value: -6, to: endDate) ?? Date()
statsCollection.enumerateStatistics(from: startDate, to: endDate) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let date = statistics.startDate
let value = quantity.doubleValue(for: HKUnit.count())
values.append(Int(value))
if date.isSameDayThan(endDate, timeZone: TimeZone.current) {
completion(values, nil)
}
} else {
values.append(0)
if values.count == 7 {
stop.pointee = true
completion(values, nil)
}
}
}
}
EDIT: Stacktrace

Why can't my iPhone get heartRate data from an Apple Watch, but the watch extension can?

I could get the data by workoutSession and HKAnchoredObjectQuery in watchkit app extension. And I also want to get heartRate and display the data on my iPhone. So I use HKSampleQuery to get by Simulator(watch and iPhone).But when I use the iPhone and watch to test. My iPhone could get the heartRate only once.
//code
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return }
// 1. Build the Predicate
let past = NSDate.distantPast() as NSDate
let now = NSDate()
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)
// 2. Build the sort descriptor to return the samples in descending order
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
// 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
// 4. Build samples query
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor])
{ (sampleQuery, HKSample, error ) -> Void in
// Get the samples
guard let heartRateSamples = HKSample as? [HKQuantitySample] else {return}
if(heartRateSamples.count > 0){
let count : Double = Double(heartRateSamples.count)
var sum = 0.0;
for quantitySample in heartRateSamples
{
let value = quantitySample.quantity.doubleValueForUnit(self.heartRateUnit);
sum += value;
}
let avg = sum/count;
self.HeartRateSum.text = String(sum)
self.Count.text = String(count)
self.SilentHeartRate.text = String(avg)
}
}
// 5. Execute the Query
self.healthStore.executeQuery(sampleQuery)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
sleep(15)
while(true){
self.getRecentHeartRate()
}
});
}
func getRecentHeartRate() ->Void{
guard let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return }
let past = NSDate.distantPast() as NSDate
let now = NSDate()
let limit = 1
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)
// 2. Build the sort descriptor to return the samples in descending order
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor])
{ (sampleQuery, HKSample, error ) -> Void in
// Get the samples
guard let heartRateSample = HKSample as? [HKQuantitySample] else {return}
guard let recentHeartRate = heartRateSample.first else{return}
let value = recentHeartRate.quantity.doubleValueForUnit(self.heartRateUnit)
dispatch_async(dispatch_get_main_queue()) {
self.heartRate.text = String(UInt16(value))
}
}
self.healthStore.executeQuery(sampleQuery)
}
You can try this for getting heartRate
func readHeartRate() {
let nowDate = NSDate()
let calendar = NSCalendar.autoupdatingCurrentCalendar()
let yearMonthDay: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day]
let components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate)
let beginOfDay: NSDate = calendar.dateFromComponents(components)!
readHRbyDate(HKObjectQueryNoLimit, startDate: beginOfDay, endDate: nowDate) { (hrData, error) in
print("heart Rate")
// print(hrData)
}
}
func readHRbyDate(latestXSamples: Int, startDate: NSDate, endDate: NSDate, completion: (((String, CGFloat), NSError!) -> Void)!) {
let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
var HRdata:(String,CGFloat) = ("N/A",0)
var bpm: Int = 0
var totalBPMforDay = [Int]()
var BPMCount: Int = 0
var sumBPM: Int = 0
let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: latestXSamples, sortDescriptors: [sortDescriptor])
{ (query, results, error) in
if let queryError = error {
print("Problem fetching HR data")
completion(("nil",0.0),queryError)
return
}else{
for result in results! {
bpm = Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)
totalBPMforDay += [Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)]
BPMCount = Int(totalBPMforDay.count)
sumBPM += Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)
let HRAvg = sumBPM / BPMCount
//HRdata = (self.getDayOfWeek(result.startDate),CGFloat(HRAvg))
let dateFormatter = MyAPIClient.sharedClient.apiClientDateFormatter() // create your date formatter
HRdata = (dateFormatter.stringFromDate(result.startDate),CGFloat(HRAvg))
print(HRdata, bpm)
}
if completion != nil {
completion(HRdata,nil)
}
}
}
executeQuery(query)
}

How to read heart rate from iOS HealthKit app using Swift?

I'm using the following Swift code.
let sampleType : HKSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let nowDate: NSDate = NSDate()
var calendar: NSCalendar = NSCalendar.autoupdatingCurrentCalendar()
let yearMonthDay: NSCalendarUnit = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit
var components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate)
var beginOfDay : NSDate = calendar.dateFromComponents(components)!
var predicate : NSPredicate = HKQuery.predicateForSamplesWithStartDate(beginOfDay, endDate: nowDate, options: HKQueryOptions.StrictStartDate)
let squery: HKStatisticsQuery = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.None) { (qurt, resul, errval) -> Void in
dispatch_async( dispatch_get_main_queue(), { () -> Void in
var quantity : HKQuantity = result.averageQuantity;
var beats : double = quantity.doubleValueForUnit(HKUnit.heartBeatsPerMinuteUnit())
// [quantity doubleValueForUnit:[HKUnit heartBeatsPerMinuteUnit]];
self.txtfldHeartRate.text = "\(beats)"
})
}
healthManager.healthKitStore.executeQuery(squery)
I get the following error message:
Cannot find an initializer for type 'HKStatisticsQuery' that accepts an argument list of type '(quantityType: HKSampleType, quantitySamplePredicate: NSPredicate, options: HKStatisticsOptions, (_, _, _) -> Void)'
Please advise me how to resolve this issue.
Reading data from ViewController (NOT apple watch extension)
Swift 5
let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(from: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
var heartRateQuery:HKSampleQuery?
/*Method to get todays heart rate - this only reads data from health kit. */
func getTodaysHeartRates() {
//predicate
let calendar = NSCalendar.current
let now = NSDate()
let components = calendar.dateComponents([.year, .month, .day], from: now as Date)
guard let startDate:NSDate = calendar.date(from: components) as NSDate? else { return }
var dayComponent = DateComponents()
dayComponent.day = 1
let endDate:NSDate? = calendar.date(byAdding: dayComponent, to: startDate as Date) as NSDate?
let predicate = HKQuery.predicateForSamples(withStart: startDate as Date, end: endDate as Date?, options: [])
//descriptor
let sortDescriptors = [
NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
]
heartRateQuery = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 25, sortDescriptors: sortDescriptors, resultsHandler: { (query, results, error) in
guard error == nil else { print("error"); return }
self.printHeartRateInfo(results: results)
}) //eo-query
health.execute(heartRateQuery!)
}//eom
/*used only for testing, prints heart rate info */
private func printHeartRateInfo(results:[HKSample]?)
{
for (_, sample) in results!.enumerated() {
guard let currData:HKQuantitySample = sample as? HKQuantitySample else { return }
print("[\(sample)]")
print("Heart Rate: \(currData.quantity.doubleValue(for: heartRateUnit))")
print("quantityType: \(currData.quantityType)")
print("Start Date: \(currData.startDate)")
print("End Date: \(currData.endDate)")
print("Metadata: \(currData.metadata)")
print("UUID: \(currData.uuid)")
print("Source: \(currData.sourceRevision)")
print("Device: \(currData.device)")
print("---------------------------------\n")
}//eofl
}//eom
Swift 3
let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKSampleQuery?
/*Method to get todays heart rate - this only reads data from health kit. */
func getTodaysHeartRates()
{
//predicate
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let components = calendar.components([.Year,.Month,.Day], fromDate: now)
guard let startDate:NSDate = calendar.dateFromComponents(components) else { return }
let endDate:NSDate? = calendar.dateByAddingUnit(.Day, value: 1, toDate: startDate, options: [])
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
//descriptor
let sortDescriptors = [
NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
]
heartRateQuery = HKSampleQuery(sampleType: heartRateType,
predicate: predicate,
limit: 25,
sortDescriptors: sortDescriptors)
{ (query:HKSampleQuery, results:[HKSample]?, error:NSError?) -> Void in
guard error == nil else { print("error"); return }
//self.printHeartRateInfo(results)
self.updateHistoryTableViewContent(results)
}//eo-query
health.executeQuery(heartRateQuery!)
}//eom
/*used only for testing, prints heart rate info */
private func printHeartRateInfo(results:[HKSample]?)
{
for(var iter = 0 ; iter < results!.count; iter++)
{
guard let currData:HKQuantitySample = results![iter] as? HKQuantitySample else { return }
print("[\(iter)]")
print("Heart Rate: \(currData.quantity.doubleValueForUnit(heartRateUnit))")
print("quantityType: \(currData.quantityType)")
print("Start Date: \(currData.startDate)")
print("End Date: \(currData.endDate)")
print("Metadata: \(currData.metadata)")
print("UUID: \(currData.UUID)")
print("Source: \(currData.sourceRevision)")
print("Device: \(currData.device)")
print("---------------------------------\n")
}//eofl
}//eom
Reading data with apple watch extension:
to execute query in apple watch, do the following:
heartRateQuery = self.createStreamingQuery()
health.executeQuery(heartRateQuery!)
don't forget the properties:
let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?
/*The below methods has no Limit, query for heart infinitely once its the query its executed */
private func createStreamingQuery() -> HKQuery
{
let queryPredicate = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)
let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query error: \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(heartRateUnit))")
}
}
}
}//eo-query
query.updateHandler =
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query-handler error : \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(heartRateUnit))")
}
}
}//eo-non_error
}//eo-query-handler
return query
}//eom
How to request authorization?
func requestAuthorization()
{
//reading
let readingTypes:Set = Set( [heartRateType] )
//writing
let writingTypes:Set = Set( [heartRateType] )
//auth request
health.requestAuthorizationToShareTypes(writingTypes, readTypes: readingTypes) { (success, error) -> Void in
if error != nil
{
print("error \(error?.localizedDescription)")
}
else if success
{
}
}//eo-request
}//eom
HKStatisticsQuery would not be my first choice for that. It is used for statistical calculations (i.e. minimum, maximum, average, sum).
You can use a simple HKQuery:
public func fetchLatestHeartRateSample(
completion: #escaping (_ samples: [HKQuantitySample]?) -> Void) {
/// Create sample type for the heart rate
guard let sampleType = HKObjectType
.quantityType(forIdentifier: .heartRate) else {
completion(nil)
return
}
/// Predicate for specifiying start and end dates for the query
let predicate = HKQuery
.predicateForSamples(
withStart: Date.distantPast,
end: Date(),
options: .strictEndDate)
/// Set sorting by date.
let sortDescriptor = NSSortDescriptor(
key: HKSampleSortIdentifierStartDate,
ascending: false)
/// Create the query
let query = HKSampleQuery(
sampleType: sampleType,
predicate: predicate,
limit: Int(HKObjectQueryNoLimit),
sortDescriptors: [sortDescriptor]) { (_, results, error) in
guard error == nil else {
print("Error: \(error!.localizedDescription)")
return
}
completion(results as? [HKQuantitySample])
}
/// Execute the query in the health store
let healthStore = HKHealthStore()
healthStore.execute(query)
}
Specifying types of constants and variables during an initialization is often redundant in Swift like in your case you has specified a parent HKSampleType type instead of its subclass HKQuantityType. So in your case just omit types declaration:
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
let nowDate = NSDate()
var calendar = NSCalendar.autoupdatingCurrentCalendar()
If you use Swift 2.0 you should also utilize array like syntax in the next line:
let yearMonthDay: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day]
Try this way, moving in the completion handler seems to resolves this for me in Xcode 6.4-
let squery = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.None, completionHandler: { (qurt, result, errval) -> Void in
dispatch_async( dispatch_get_main_queue(), { () -> Void in
var quantity : HKQuantity = result.averageQuantity();
var beats : Double = quantity.doubleValueForUnit(HKUnit.atmosphereUnit())
// [quantity doubleValueForUnit:[HKUnit heartBeatsPerMinuteUnit]];
})
})
Note: I was seeing some compiler errors within closure, so have changed 2 lines to just ensure compilation-
var quantity : HKQuantity = result.averageQuantity();
var beats : Double = quantity.doubleValueForUnit(HKUnit.atmosphereUnit())
You should be using HKQuantityType instead of HKSampleType in your query:
let squery: HKStatisticsQuery = HKStatisticsQuery(quantityType: HKQuantityTypeIdentifierHeartRate, quantitySamplePredicate: predicate, options: HKStatisticsOptions.None) { (qurt, resul, errval) -> Void in

Resources