过滤不属于我的应用程序的HKSample数据

时间:2015-11-30 08:28:41

标签: iphone swift health-kit hkhealthstore

在我目前的项目中,我需要与我的应用程序同步HealthKit示例。我从HealthKit获取样本数据并将一些应用程序生成的样本写回HealthKit。使用以下功能获取I - 用于: -

private func readHealthKitSample(sampleType:HKSampleType, limit: Int, startDate: NSDate, endDate: NSDate, completion: (([HKSample]?, NSError!) -> Void)!){

    let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate:endDate, options: .None)

    // 2. Build the sort descriptor to return the samples in descending order
    let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)

    // 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
    let limit = limit

    // 4. Build samples query
    let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor])
        { (sampleQuery, results, error ) -> Void in

            if let error = error {
                self.Logger.error("HealthKit Sample Data Fetch Error: \(error.localizedDescription)")
                completion(nil , error)
                return;
            } else {
               // self.Logger.debug("HealthKit Sample Data Fetch SUCCESS: \(results)")
            }

            // Execute the completion closure
            if completion != nil {
                completion(results,nil)
            }
    }
    // 5. Execute the Query
    self.healthKitStore.executeQuery(sampleQuery)
}

我的应用程序要求不要将自己编写的样本考虑到HealthKit Store。那么,有没有办法以这样的方式过滤样本数据,以至于我可以避免接收由我的应用程序编写的样本并仅考虑其他应用程序编写的样本?

1 个答案:

答案 0 :(得分:2)

您可以使用HKSource过滤掉您自己的应用和NSCompoundPredicate,将其与现有的谓词过滤器结合使用:

let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate:endDate, options: .None)
let myAppPredicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource()) // This would retrieve only my app's data
let notMyAppPredicate = NSCompoundPredicate(notPredicateWithSubpredicate: myAppPredicate) // This will retrieve everything but my app's data
let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [mostRecentPredicate, notMyAppPredicate])

let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: queryPredicate, limit: limit, sortDescriptors: [sortDescriptor]) {
    // Process results here...
}