1

I'm retrieving sleepAnalysis data from HealthKit and want to store these samples in a global array but once I'm outside the scope of the HKSampleQuery, self.globalVariable goes back to it's initial value of an empty array. How can I retrieve these values outside of the query scope?

if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
        let query = HKSampleQuery(sampleType: sleepType, predicate: nil,limit: 90, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error)-> Void in
            if error != nil {
                return
            }
            if let result = tmpResult {
                for item in result {
                    if let sample = item as? HKCategorySample {
                        samples.append(sample)
                    }
                }
            }
       healthStore.execute(query)
       }
}

Outside of the let query scope, samples is nil.

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
  • You should add some code to your question so we can see exactly what you're doing and why it might not be working. – Paolo Jun 01 '17 at 13:35
  • @Paolo Example added – octopathTraveller Jun 01 '17 at 13:46
  • 1
    Are you by any chance trying to access `samples` before the query has finished executing? The query won't be instantaneous so if you check `samples` right after doing `healthStore.execute(query)` it will still be `nil`. Look at the example code here: https://developer.apple.com/reference/healthkit/hksamplequery You can see that they have `dispatch_async(dispatch_get_main_queue())` to actually use the data (in this case reloading a table view). – Paolo Jun 01 '17 at 13:50
  • Also your `healthStore.execute(query)` is inside the completion handler so it won't get called. – Paolo Jun 01 '17 at 13:56

0 Answers0