在Apple Watch上从HealthKit请求数据

loa*_*djd 4 ios healthkit watchkit

我有一个手表套件应用程序试图从Apple手表上的界面控制器请求HealthKit权限,但是当我运行应用程序时,我从未被要求获得许可,并且该应用程序默认没有健康套件权限.如何让苹果申请HealthKit权限?

leh*_*058 16

您可以从watchOS应用程序请求访问健康工具包,但用户需要在iPhone上接受请求.为此,您可以像往常一样请求在watchOS应用上访问健康工具包:

var healthKitTypesToRead = Set<HKObjectType>()
// TODO: add your read types here

var healthKitTypesToWrite = Set<HKSampleType>()
// TODO: add your write types here

healthStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
    // TODO: Handle success or failure
}
Run Code Online (Sandbox Code Playgroud)

然后你需要在你的iOS应用程序中将它添加到你的AppDelegate:

func applicationShouldRequestHealthAuthorization(application: UIApplication) {
    let healthStore = HKHealthStore()
    healthStore.handleAuthorizationForExtensionWithCompletion { (success, error) -> Void in
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您在手表上向用户请求运行状况工具包权限时,他们将在手表上获得一个权限对话框,告诉他们接受或拒绝iPhone上的权限.当他们转到他们的iPhone时,您的应用程序的健康工具包权限对话框将等待.一旦他们在iPhone上设置了他们的首选项,您的requestAuthorizationToShareTypes完成处理程序将在您的Apple Watch上调用.