简体   繁体   中英

Swift 4 Get preferredUnit from HealthKit

I´ma beginner in Swift and I tried to get the User preferred Unit from HealthKit.

Apple offers this function for it

func preferredUnits(for quantityTypes: Set<HKQuantityType>, 
     completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void)

Source

But I really have no idea how to implement it correctly. Atm the function do nothing in my App.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

    let bloodGlucose = HKObjectType.quantityType(forIdentifier: .bloodGlucose)
    let HKQuantitySet: Set<HKSampleType> = [bloodGlucose!]        

    self.preferredUnits(for: HKQuantitySet as! Set<HKQuantityType>, completion: { (preferedUnit, error) in
            print(preferedUnit)
        })

    return true
}



func preferredUnits(for quantityTypes: Set<HKQuantityType>,
                completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void){

}

I´m pretty sure I am totally wrong about this.

Does someone know how to implement the function correctly? Not only for bloodglucose , in general, would be nice.

You need to call the preferredUnits function an instance of HKHealthStore . Your code is just calling a function that you have declared with the same signature that does nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM