HealthKit学习

HealthKit是iOS8的特性,用来提供存储和获取用户健康数据

1。获取HealthKit的授权,在Targets-Capabilities打开HealthKit的开关

  • 如果是app支持iOS8以下或者需要支持pad等不支持healthKit,需要在info。plist里删除掉healthKit的选项,或者会被苹果拒
    并请求这些应用装不上App
    如下图
2.png

最后的配置图下

HealthKit学习_第1张图片
1.png

2。指定HealthKit的数据类型,并授权

HealthKit的数据类型都是HKObjectType的子类,提供了5个方法用来获取HKObjectType子类的类型,再

  public class func quantityTypeForIdentifier(identifier: String) -> HKQuantityType?
  public class func categoryTypeForIdentifier(identifier: String) -> HKCategoryType?
  public class func characteristicTypeForIdentifier(identifier: String) -> HKCharacteristicType?
  public class func correlationTypeForIdentifier(identifier: String) -> HKCorrelationType?
  public class func workoutType() -> HKWorkoutType

identifier类型可通过https://developer.apple.com/library/watchos/documentation/HealthKit/Reference/HealthKit_Constants/#//apple_ref/doc/constant_group/Body_Measurements 查看

授权代码

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        healthStore = HKHealthStore()
        if HKHealthStore.isHealthDataAvailable() {
            self.authorizeHealthKit()
        }

    }

    func authorizeHealthKit() {

        let readType:Set = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!]
        let writeType:Set = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!]

        //获取授权
        self.healthStore.requestAuthorizationToShareTypes(writeType, readTypes: readType) { (x:Bool, y:NSError?) -> Void in

        }

    }

你可能感兴趣的:(HealthKit学习)