Why doesn't HKAnchoredObjectQuery with enableBackgroundDeliveryForType always fire when app is in the background?

情到浓时终转凉″ 提交于 2019-12-03 20:42:37

I suggest using an HKObserverQuery and setting it up carefully.

There is an algorithm that watches how and when you call the "completion" handler of the HKObserverQuery when you have background delivery enabled. The details of this are vague unfortunately. Someone on the Apple Dev forums called it the "3 strikes" rule but Apple hasn't published any docs that I can find on it's behavior.

https://forums.developer.apple.com/thread/13077

One thing I have noticed is that, if your app is responding to a background delivery with an HKObserverQuery, creating an HKAnchoredObjectQuery, and setting the UpdateHandler in that HKAnchoredObjectQuery, this UpdateHandler will often cause multiple firings of the callback. I suspected that perhaps since these additional callbacks are being executed AFTER you have already told Apple that you have completed you work in response to the background delivery, you are calling the completion handler multiple times and maybe they ding you some "points" and call you less often for bad behavior.

I had the most success with getting consistent callbacks by doing the following:

  1. Using an ObserverQuery and making the sure the call of the "completion" handler gets called once and at the very end of your work.
  2. Not setting an update handler in my HKAnchoredObjectQuery when running in the background (helps achieve 1).
  3. Focusing on making my query handlers, AppDelegate, and ViewController are as fast as possible. I noticed that when I reduced all my callbacks down to just a print statement, the callbacks from HealthKit came immediately and more consistently. So that says Apple is definitely paying attention to execution time. So try to statically declare things where possible and focus on speed.

I have since moved on to my original project which uses Xamarin.iOS, not swift, so I haven't kept up with the code I originally posted. But here is an updated (and untested) version of that code that should take these changes into account (except for the speed improvements):

//
//  HKClient.swift
//  HKTest

import UIKit
import HealthKit

class HKClient : NSObject {

var isSharingEnabled: Bool = false
let healthKitStore:HKHealthStore? = HKHealthStore()
let glucoseType : HKObjectType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!

override init(){
    super.init()
}

func requestGlucosePermissions(authorizationCompleted: (success: Bool, error: NSError?)->Void) {

    let dataTypesToRead : Set<HKObjectType> = [ glucoseType ]

    if(!HKHealthStore.isHealthDataAvailable())
    {
        // let error = NSError(domain: "com.test.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey: "Healthkit is not available on this device"])
        self.isSharingEnabled = false
        return
    }

    self.healthKitStore?.requestAuthorizationToShareTypes(nil, readTypes: dataTypesToRead){(success, error) -> Void in
        self.isSharingEnabled = true
        authorizationCompleted(success: success, error: error)
    }
}

func startBackgroundGlucoseObserver( maxResultsPerQuery: Int, anchorQueryCallback: ((source: HKClient, added: [String]?, deleted: [String]?, newAnchor: HKQueryAnchor?, error: NSError?)->Void)!)->Void {
    let onBackgroundStarted = {(success: Bool, nsError : NSError?)->Void in
        if(success){
            //Background delivery was successfully created.  We could use this time to create our Observer query for the system to call when changes occur.  But we do it outside this block so that even when background deliveries don't work,
            //we will have the observer query working when are in the foreground at least.
        } else {
            debugPrint(nsError)
        }


        let obsQuery = HKObserverQuery(sampleType: self.glucoseType as! HKSampleType, predicate: nil) {
            query, completion, obsError in

            if(obsError != nil){
                //Handle error
                debugPrint(obsError)
                abort()
            }

            var hkAnchor = self.getAnchor()
            if(hkAnchor == nil) {
                hkAnchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
            }

            self.getGlucoseSinceAnchor(hkAnchor, maxResults: maxResultsPerQuery, callContinuosly:false, callback: { (source, added, deleted, newAnchor, error) -> Void in
                anchorQueryCallback(source: self, added: added, deleted: deleted, newAnchor: newAnchor, error: error)

                //Tell Apple we are done handling this event.  This needs to be done inside this handler
                completion()
            })
        }

        self.healthKitStore?.executeQuery(obsQuery)
    }

    healthKitStore?.enableBackgroundDeliveryForType(glucoseType, frequency: HKUpdateFrequency.Immediate, withCompletion: onBackgroundStarted )
}

func getGlucoseSinceAnchor(anchor:HKQueryAnchor?, maxResults:Int, callContinuosly:Bool, callback: ((source: HKClient, added: [String]?, deleted: [String]?, newAnchor: HKQueryAnchor?, error: NSError?)->Void)!){

    let sampleType: HKSampleType = glucoseType as! HKSampleType
    var hkAnchor: HKQueryAnchor;

    if(anchor != nil){
        hkAnchor = anchor!
    } else {
        hkAnchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
    }

    let onAnchorQueryResults : ((HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, NSError?) -> Void)! = {
        (query:HKAnchoredObjectQuery, addedObjects:[HKSample]?, deletedObjects:[HKDeletedObject]?, newAnchor:HKQueryAnchor?, nsError:NSError?) -> Void in

        var added = [String]()
        var deleted = [String]()

        if (addedObjects?.count > 0){
            for obj in addedObjects! {
                let quant = obj as? HKQuantitySample
                if(quant?.UUID.UUIDString != nil){
                    let val = Double( (quant?.quantity.doubleValueForUnit(HKUnit(fromString: "mg/dL")))! )
                    let msg : String = (quant?.UUID.UUIDString)! + " " + String(val)
                    added.append(msg)
                }
            }
        }

        if (deletedObjects?.count > 0){
            for del in deletedObjects! {
                let value : String = del.UUID.UUIDString
                deleted.append(value)
            }
        }

        if(callback != nil){
            callback(source:self, added: added, deleted: deleted, newAnchor: newAnchor, error: nsError)
        }
    }
    let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: nil, anchor: hkAnchor, limit: Int(maxResults), resultsHandler: onAnchorQueryResults)
    if(callContinuosly){
        //The updatehandler should not be set when responding to background observerqueries since this will cause multiple callbacks
        anchoredQuery.updateHandler = onAnchorQueryResults
    }
    healthKitStore?.executeQuery(anchoredQuery)
}

let AnchorKey = "HKClientAnchorKey"
func getAnchor() -> HKQueryAnchor? {
    let encoded = NSUserDefaults.standardUserDefaults().dataForKey(AnchorKey)
    if(encoded == nil){
        return nil
    }
    let anchor = NSKeyedUnarchiver.unarchiveObjectWithData(encoded!) as? HKQueryAnchor
    return anchor
}

func saveAnchor(anchor : HKQueryAnchor) {
    let encoded = NSKeyedArchiver.archivedDataWithRootObject(anchor)
    NSUserDefaults.standardUserDefaults().setValue(encoded, forKey: AnchorKey)
    NSUserDefaults.standardUserDefaults().synchronize()
}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!