Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

Healthkit enableBackgroundDeliveryForType is unavailable, unable to calculate heart rate every hour

I am trying to trigger enableBackgroundDeliveryForType after creating a HKObserverQuery , but I realised that even the method itself is disabled .

/*!
 @method        enableBackgroundDeliveryForType:frequency:withCompletion:
 @abstract      This method enables activation of your app when data of the type is recorded at the cadence specified.
 @discussion    When an app has subscribed to a certain data type it will get activated at the cadence that is specified
                with the frequency parameter. The app is still responsible for creating an HKObserverQuery to know which
                data types have been updated and the corresponding fetch queries. Note that certain data types (such as
                HKQuantityTypeIdentifierStepCount) have a minimum frequency of HKUpdateFrequencyHourly. This is enforced
                transparently to the caller.
 */

So how to trigger a job which will check Heart rate every hour .

 healthStore.enableBackgroundDeliveryForType(sampleType, frequency: .Immediate, withCompletion: {(succeeded: Bool, error: NSError?) in

        if succeeded{
            print("Enabled background delivery of weight changes")
        } else {
            if let theError = error{
                print("Failed to enable background delivery of weight changes. ")
                print("Error = \(theError)")
            }
        }
    })

Following is the query I am running to get the sample.

        let sampleType =  HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!

        //let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)



        let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
            query, completionHandler, error in

            if error != nil {

                // Perform Proper Error Handling Here...
                print("*** An error occured while setting up the stepCount observer. ***")
                abort()
            }else{
                print("sampleType ",sampleType)
            }
            self.heightChangedHandler()
            completionHandler()
        }

func heightChangedHandler(){
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate,
                ascending: true)

            let sampleType =  HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
            let query = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { (query: HKSampleQuery, results: [HKSample]?, error: NSError?) -> Void in

                guard let results = results where results.count > 0 else {
                    print("Could not read the user's weight")
                    print("or no weight data was available")
                    return
                }

                for sample in results as! [HKQuantitySample]{

                    let heartRate = sample.quantity
                    let heartRateDouble = heartRate.doubleValueForUnit(self.countPerMinuteUnit)
                    print("Sample ",sample.quantity ," tyoe ",sample.quantityType," heartRateDouble ",heartRateDouble)

                }

            }

            healthStore.executeQuery(query)
}

Upvotes: 1

Views: 1338

Answers (2)

Mikhail Amchei
Mikhail Amchei

Reputation: 21

2 things, one the method you are trying to access is currently for iPhone only. Apple watch does not even have a background state yet, just inactive state in place of that. Second apple promised that watch app extensions while running workouts would allow to stay in the foreground and that is generally true until the user's wrist goes down :( anyway good luck and hopefully you figured how to implement for your purpose..

I am not familiar with the process but you may just schedule a complication to update every hour where you can try to extract last known heart rate object from health store.. anyway never tried it for my purposes and am almost sure there is some things that will need to be changed but just a thought.

OR the thing I've just thought of implementing.. try to catch changes to the store on the phone and then send data to the watch through background transfer. Basically you can make updates immediate there or daily.. up to you and then send it to the watch from phone, won't be a bummer for backgrounded apps I hope.

Upvotes: 2

Allan
Allan

Reputation: 7353

There is no way to schedule watchOS 2.0 apps to launch in the background periodically to query for HealthKit data. Apps for watchOS 2.0 may generally only run in the foreground while the screen of the watch is on.

Upvotes: 3

Related Questions