React Native模块-导出Swift-HealthKit

时间:2018-10-24 15:03:19

标签: objective-c swift react-native

我有一个React Native App(0.57),正在尝试访问HealthKit并创建查询以获取每日步数。

幸运的是,我可以使用授权功能,但是似乎无法获取步数。

NativeModules.Steps.checkAuthorization()->有效!

我在steps.swift文件中尝试了2种不同的功能,但是似乎都崩溃了我的应用程序。我不知道swift代码是错误的还是我在网桥中的定义是错误的。任何帮助将不胜感激!

getTodaysSteps函数

@objc(getTodaysSteps:)
func getTodaysSteps(completion: @escaping (Double) -> Void) {
  let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

  let now = Date()
  let startOfDay = Calendar.current.startOfDay(for: now)
  let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

  let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
    guard let result = result, let sum = result.sumQuantity() else {
      completion(0.0)
      return
    }
    completion(sum.doubleValue(for: HKUnit.count()))
  }

  storage.execute(query)
}

recentSteps函数

  @objc(recentSteps:failure:)
  func recentSteps(success: @escaping (Double) -> (), failure: @escaping (Error?) -> () ) {
    guard let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else {
      failure(nil)
      return
    }

    let predicate = HKQuery.predicateForSamples(withStart: Date(), end: Date(), options: [])
    let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in

      if let error = error {
        failure(error)
      }

      var steps: Double = 0

      results?.forEach { result in
        if let quantity = result as? HKQuantitySample { // ??? not sure if result (type HKSample) will convert to type HKQuantitySample
          steps += quantity.quantity.doubleValue(for: HKUnit.count())
        }
      }

      success(steps)
    }

    storage.execute(query)
  }
}

不幸的是,这些似乎都不起作用。当我调用这些函数时,应用程序崩溃。

桥文件

这是我在网桥文件中定义它们的方式。我希望我做错了。

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(Steps, NSObject)
  RCT_EXTERN_METHOD(checkAuthorization)
  RCT_EXTERN_METHOD(getTodaysSteps:)
  RCT_EXTERN_METHOD(recentSteps:(RCTPromiseResolveBlock)resolver rejecter:(RCTPromiseRejectBlock)rejecter)
@end

JavaScript Land

我正在React Native应用程序中调用如下函数:

componentWillMount () {
  console.log(NativeModules, 'NativeModules in mounting')
  NativeModules.Steps.checkAuthorization()
  NativeModules.Steps.getTodaysSteps()
  NativeModules.Steps.recentSteps()
}

任何帮助将不胜感激!

0 个答案:

没有答案