Swift - HealthKit不会进行身份验证

时间:2017-05-28 22:39:56

标签: swift health-kit

我正在尝试创建一个基本脚本,它将从iOS上的HealthKit中拉出我的日常步骤,但是当页面被触发时 - 没有任何反应。它应该请求读取HealthKit数据的权限,我无法解决我出错的地方。

这是我的代码:

import Foundation
import UIKit
import HealthKit
class HealthKitPage: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    class HealthKitManager {
        let HealthStore = HKHealthStore()

        func AuthoriseHealthKit() -> Bool {
            var isEnabled = true

            if HKHealthStore.isHealthDataAvailable() {
                let StepCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount))

                let DataTypesToWrite = NSSet(object: StepCount)
                let DataTypesToRead = NSSet(object: StepCount)

                HealthStore.requestAuthorization(toShare: nil, read: (StepCount as! Set<HKObjectType>)) {
                    (success, error) -> Void in
                    isEnabled = success
                }
            }else{
                isEnabled = false
            }

            return isEnabled
        }
    }

有人可以提出任何建议吗?

2 个答案:

答案 0 :(得分:0)

import UIKit
import HealthKit
class HealthKitPage : UIViewController
{
 let healthStore: HKHealthStore = HKHealthStore()

 override func viewDidLoad()
 {
     var shareTypes = Set<HKSampleType>()

shareTypes.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)



        var readTypes = Set<HKObjectType>()
        readTypes.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)


        healthStore.requestAuthorizationToShareTypes(shareTypes, readTypes: readTypes) { (success, error) -> Void in
            if success {
                print("success")
            } else {
                print("failure")
            }

            if let error = error { print(error) }
        }


}

}

答案 1 :(得分:0)

我能够使用Himali的答案来解决这个问题,但它需要转换为Swift 3,这是我的工作文件:

import Foundation
import UIKit
import HealthKit


import UIKit
import HealthKit
class HealthKitPage : UIViewController
{
      let healthStore: HKHealthStore = HKHealthStore()

      override func viewDidLoad()
      {
                var shareTypes = Set<HKSampleType>()

                shareTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)



                var readTypes = Set<HKObjectType>()
                readTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)


                healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
                          if success {
                                    print("success")
                          } else {
                                    print("failure")
                          }

                          if let error = error { print(error) }


                }





      }