Как считывать жизненно важные данные приложения «Здоровье» в другие приложения на iOS с помощью Healthkit

Я использую устройства iHealth, чтобы получать жизненно важные данные с устройства, используя там приложение iHealth, эти данные хранятся в приложении Health. Я настроил свое приложение для связи с приложением Health, но не знаю, как передать сохраненные данные о здоровье в свое собственное приложение.

Поскольку нет примеров для этой проблемы, и документация также не содержит подробной информации об этом.


person kaushaw    schedule 20.02.2015    source источник
comment
Видео HealthKit с WWDC этого года очень полезно! developer.apple.com/videos/wwdc/2014/#203   -  person Dave Leverton    schedule 20.02.2015


Ответы (2)


Если вы (или пользователь) вашего приложения предоставили вашему приложению доступ для чтения того, что iHealth сохранило в базе данных HealthKit, вы можете запросить его с помощью API HealthKit.

// 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)
}
person cmollis    schedule 02.03.2015

К вашему сведению, после включения Healthkit в вашем AppID вам необходимо пройти аутентификацию в магазине здоровья.

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

person Senthilkumar    schedule 14.09.2015