2016-11-18 80 views

回答

1

創建healthkit實例

let healthKitStore:HKHealthStore = HKHealthStore() 

請求允許

func requestPermissions(completion: @escaping ((_ success:Bool, _ error:Error?) -> Void)){ 
    let healthKitTypesToRead : Set<HKSampleType> = [ 
     HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!, 
     HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!, 
    ] 

    let healthKitTypesToWrite: Set<HKSampleType> = [ 
     HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!, 
     HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!, 
    ] 

    if !HKHealthStore.isHealthDataAvailable() { 
     print("Error: HealthKit is not available in this Device") 
     completion(false, error) 
     return 
    } 

    healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in 
     completion(success,error) 
    } 

} 

讀取高度

let heightType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)! 
let query = HKSampleQuery(sampleType: heightType, predicate: nil, limit: 1, sortDescriptors: nil) { (query, results, error) in 
    if let result = results?.first as? HKQuantitySample{ 
     print("Height => \(result.quantity)") 
    }else{ 
     print("OOPS didnt get height \nResults => \(results), error => \(error)") 
    } 
} 
self.healthKitStore.execute(query) 

寫作身高

let height = YOUR_HEIGHT 

if let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) { 
    let date = Date() 
    let quantity = HKQuantity(unit: HKUnit.inch(), doubleValue: height!) 
    let sample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date) 
    self.healthKitStore.save(sample, withCompletion: { (success, error) in 
     print("Saved \(success), error \(error)") 
    }) 
} 

現在,如果你想讀,寫權重,然後只需用

HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) 

注意:不要忘了添加這些權限

隱私 - 健康更新使用說明

隱私 - 健康分享使用說明

希望這對其他仍在尋找它的人有幫助

+0

我已經在iPhone的默認應用程序運行狀態中添加了高度。但是我想從運行狀況高度到我的應用程序,我得到零值。你能給我一個方向嗎? –

+0

@HimaliShah:我已經提到了閱讀代碼,但不能幫助,如果我不能看到的代碼,發表一個問題,你的代碼寫的檢索它 –

相關問題