ios - 找不到类型的初始值设定项

标签 ios swift swift2 xcode7 healthkit

    let endDate = NSDate()
    let startDate = NSDate()
    let v : Float?
    let stepsCount:HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!
    let predicate:NSPredicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)

    let query = HKQuantitySample(sampleType: stepsCount, predicate: predicate, limit: 1, sortDescriptors: nil, resultsHandler: {
        (query, results, error) in
        if results == nil {
            print(error)
        }
        v = result.first.Quantity

    })
    healthStore.executeQuery(query)

Cannot find an initializer for type 'HKQuantitySample' that accepts an argument list of type '(sampleType: HKQuantityType, predicate: NSPredicate, limit: Int, sortDescriptors: nil, resultsHandler: (_, _, _) -> _)'

最佳答案

只需将 HKQuantitySample 替换为 HKSampleQuery 即可正常工作。

有关更多信息,请参阅 THIS教程。

在哪里可以找到示例代码:

func readMostRecentSample(sampleType:HKSampleType , completion: ((HKSample!, NSError!) -> Void)!)
{

  // 1. Build the Predicate
  let past = NSDate.distantPast() as! NSDate
  let now   = NSDate()
  let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)

  // 2. Build the sort descriptor to return the samples in descending order
  let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
  // 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
  let limit = 1

  // 4. Build samples query
  let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor])
    { (sampleQuery, results, error ) -> Void in

      if let queryError = error {
        completion(nil,error)
        return;
      }

      // Get the first sample
      let mostRecentSample = results.first as? HKQuantitySample

      // Execute the completion closure
      if completion != nil {
        completion(mostRecentSample,nil)
      }
  }
  // 5. Execute the Query
  self.healthKitStore.executeQuery(sampleQuery)
}

关于ios - 找不到类型的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874308/

相关文章:

ios - 如何在放大/缩小图像时在图像上显示相对 View ?Footprint : Indoor Positioning with Core Location

ios - Swift 将字符串转换为 UIIMAGE

objective-c - Swift 覆盖从 Objective-C 继承的类中的 init()

ios - 无法在 UIStackview 响应式(Reactive)和声明式 swift 中转换类型的值

ios - 为预览图层设置边框会导致边框设置不正确

ios - 如何在 Swift 中创建连接的 slider ?

将 NSData 复制到 UnsafeMutablePointer<Void>

iphone - 获取国家域名代码

ios - 在 Objective-C 中的方法之间传递信息

ios - 如何使用 SwiftUI 将图像和标签添加到选项卡栏项目