Search code examples
swift2healthkithksamplequery

Swift2 - HKSampleQuery


let hkSampleType:HKSampleType = HKSampleType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)!
let query = HKSampleQuery(sampleType: hkSampleType, predicate: predicate, limit: 80, sortDescriptors: nil, resultsHandler: { (query:HKSampleQuery, results:[HKSample]!, error:NSError!) -> Void in
    //code
})

this is it but I receive an error: Cannot find an initializer for type 'HKSampleQuery' that accepts an argument list of type '(sampleType: HKSampleType, predicate: NSPredicate, limit: Int, sortDescriptors: nil, resultsHandler: (HKSampleQuery, [HKSample]!, NSError!) -> Void)'

How will be the right syntax ?


Solution

  • I'm not an expert in either Swift or HealthKit, but this compiles in Xcode 7:

    let hkSampleType:HKSampleType = HKSampleType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)!
    let query = HKSampleQuery(sampleType: hkSampleType, predicate: nil, limit: 80, sortDescriptors: nil, resultsHandler: { (query:HKSampleQuery, results:[HKSample]?, error:NSError?) -> Void in
        //code
    })
    

    In the closure, results and error are optionals in iOS 9. You declared them as unwrapped.

    One thing I'm not sure about is that can you use HKSampleQuery for HKCorrelation. Here is the correct declaration for HKCorrelationQuery in case you need it:

    let corralationType = HKCorrelationType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)!
    let query = HKCorrelationQuery(type: corralationType, predicate: nil, samplePredicates: nil) { (query: HKCorrelationQuery, results: [HKCorrelation]?, error: NSError?) -> Void in
    
    }