如何使用Healthkit将Health应用程序重要数据读入ios中的其他应用程序

时间:2015-02-20 10:21:21

标签: ios health-kit hkhealthstore

我正在使用iHealth设备通过iHealth应用程序从设备获取生命值,这些数据存储在Health应用程序中。我已将我的应用程序配置为与Health应用程序通信,但我不知道如何将存储的健康数据存储到我自己的自定义应用程序中。

由于此问题没有示例,文档也没有提供有关它的深入信息。

2 个答案:

答案 0 :(得分:0)

只要您的应用程序(或用户)已授予您的应用程序访问权限以阅读HealthHit数据库中存储的iHealth,您就可以使用HealthKit API进行查询。

// 1. these are the items we want to read
let healthKitTypesToRead = NSSet(array:[
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)
])

// 2. these are the items we want to write
let healthKitTypesToWrite = NSSet(array:[
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)
])

// 3.  Request HealthKit authorization
    healthKitStore!.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in

            if( completion != nil )
            {
                if (success == true) {
                    self.initialized = true
                }
                completion(success:success,error:error)
            }
    }

然后您可以查询数据:

// 4. Build the Predicate
let past = NSDate.distantPast() as NSDate
let now   = NSDate()
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)

    //  Build the sort descriptor to return the samples in descending order
    let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
    //  we want to limit the number of samples returned by the query to just 1 (the most recent)
    let limit = 1

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

            if let queryError = error {
                completion(nil,error)
                return;
            }

            // Get the first sample
            let mostRecentSample = results.first as? HKQuantitySample

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

答案 1 :(得分:0)

仅供参考,在您的AppID中启用Healthkit后。您必须从健康商店验证要求。

let healthKitStore:HKHealthStore = HKHealthStore()

    func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!)
    {

        // 1. Set the types you want to read from HK Store
        var healthKitTypesToRead = self.dataTypesToRead() as! Set<NSObject>

        // 2. Set the types you want to write to HK Store
        var healthKitTypesToWrite = self.dataTypesToWrite() as! Set<NSObject>


        // 3. If the store is not available (for instance, iPad) return an error and don't go on.
        if !HKHealthStore.isHealthDataAvailable()
        {
            let error = NSError(domain: "com.domain.....", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
            if( completion != nil )
            {
                completion(success:false, error:error)
            }
            return;
        }
        else
        {

             // 4.  Request HealthKit authorization
            healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes:healthKitTypesToRead, completion: { (success, error) -> Void in

                if( completion != nil )
                {
                    completion(success:success,error:error)
                }

            })


        }

    }

有用的链接如下:

https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/index.html#//apple_ref/doc/uid/TP40014707

https://en.wikipedia.org/wiki/Health_%28application%29

http://www.raywenderlich.com/86336/ios-8-healthkit-swift-getting-started

https://developer.apple.com/videos/wwdc/2014/#203