HealthKit是iOS8的特性,用來提供存儲和獲取用戶健康數(shù)據(jù)
1。獲取HealthKit的授權(quán),在Targets-Capabilities打開HealthKit的開關(guān)
- 如果是app支持iOS8以下或者需要支持pad等不支持healthKit,需要在info。plist里刪除掉healthKit的選項,或者會被蘋果拒
并請求這些應(yīng)用裝不上App
如下圖

2.png
最后的配置圖下

1.png
2。指定HealthKit的數(shù)據(jù)類型,并授權(quán)
HealthKit的數(shù)據(jù)類型都是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 查看
授權(quán)代碼
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
healthStore = HKHealthStore()
if HKHealthStore.isHealthDataAvailable() {
self.authorizeHealthKit()
}
}
func authorizeHealthKit() {
let readType:Set<HKObjectType> = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!]
let writeType:Set<HKSampleType> = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!]
//獲取授權(quán)
self.healthStore.requestAuthorizationToShareTypes(writeType, readTypes: readType) { (x:Bool, y:NSError?) -> Void in
}
}