0

I'm trying to learn Apple HealthKit, and my current goal is to make my application observe HK queries for certain sample types while it's in the background. I can initialize an observerquery with sampletype and predicate:

let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {...}

But when I try to use a custom updateHandler in initialization, XCode raises an issue:

func setUpBackgroundDelivery() {

    guard let sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose) as HKSampleType! else {
        ...
    }

    self.healthKitStore.enableBackgroundDeliveryForType(sampleType, frequency: .Immediate) { (success, error) in
        ...
    }

    let updateHandler: (HKObserverQuery, HKObserverQueryCompletionHandler, NSError?) -> Void = {
        query, completionHandler, error in
        ...
        NSLog("HealthKit Background Delivery received")
        completionHandler()
    }

    let query = HKObserverQuery(sampleType: sampleType, predicate: nil, updateHandler: updateHandler) {
        query, completionHandler, error in
        ...
        completionHandler()   
    }
    healthKitStore.executeQuery(query)
}

Issue being:

...'(sampleType: HKSampleType, predicate: _, updateHandler: (HKObserverQuery, HKObserverQueryCompletionHandler, NSError?) -> Void, (_, _, _) -> ())' (aka '(sampleType: HKSampleType, predicate: _, updateHandler: (HKObserverQuery, () -> (), Optional) -> (), (_, _, _) -> ())') is not convertible to '(sampleType: HKSampleType, predicate: NSPredicate?, updateHandler: (HKObserverQuery, HKObserverQueryCompletionHandler, NSError?) -> Void)' (aka '(sampleType: HKSampleType, predicate: Optional, updateHandler: (HKObserverQuery, () -> (), Optional) -> ())'), tuples have a different number of elements

Patrick
  • 1,629
  • 5
  • 23
  • 44
Julius
  • 409
  • 4
  • 19
  • 1
    A long time ago I answer a question related with backgrounds notifications and `HKObserverQuery`, I think you can benefit a lot from it and from the other answer provided with a detailed explanation of the times of update and more http://stackoverflow.com/questions/26375767/healthkit-background-delivery-when-app-is-not-running – Victor Sigler Jun 16 '16 at 13:04
  • I think I have misunderstood the syntax. Seems like if I include the updateHandler argument, I'm going to have to remove the following closures. Thanks for the comment, it helped me to realize this. – Julius Jun 16 '16 at 21:46

1 Answers1

1

You should not specify both updateHandler and a trailing closure. Only one of them can be the argument for the update handler block parameter of the initializer.

Allan
  • 7,039
  • 1
  • 16
  • 26