将swift2.x转换为swift3题

Convert swift 2.x to swift 3 problems

我已经制作了这个函数来获取每天的所有步骤,但我想将这个函数从 swift 2.x 转换为 swift 3。但是我卡在了 2 个不同的点.

let anchorDate = calendar.dateComponents(anchorComponents)  

我收到此错误: 无法使用列表类型 (Datecomponents) 的参数调用 dateCompontents


关于这一点:

let stepsQuery = HKStatisticsCollectionQuery(quantityType: HKQuantityType, quantitySamplePredicate: nil, options: .CumulativeSum, anchorDate: anchorComponents!, intervalComponents: interval)

错误: 无法将类型 HKQuantityType.Type 的值转换为预期的参数类型 HKQuantityType。


完整功能:

func getDailySteps(){
            let calendar = NSCalendar.current
            let interval = NSDateComponents()
            interval.day = 1

        var anchorComponents = calendar.dateComponents([.day , .month , .year], from: NSDate() as Date)
        anchorComponents.hour = 0
        let anchorDate = calendar.dateComponents(anchorComponents)

        // Define 1-day intervals starting from 0:00
        let stepsQuery = HKStatisticsCollectionQuery(quantityType: HKQuantityType, quantitySamplePredicate: nil, options: .CumulativeSum, anchorDate: anchorComponents!, intervalComponents: interval)

        // Set the results handler
        stepsQuery.initialResultsHandler = {query, results, error in
            let endDate = NSDate()
            let startDate = calendar.dateByAddingUnit(.Day, value: -7, toDate: endDate, options: [])
            if let myResults = results{                                                                             myResults.enumerateStatisticsFromDate(startDate!, toDate: endDate) { statistics, stop in
                if let quantity = statistics.sumQuantity(){
                    let date = statistics.startDate
                    let steps = quantity.doubleValueForUnit(HKUnit.countUnit())
                    print("\(date): steps = \(steps)")
                    //NOTE: If you are going to update the UI do it in the main thread
                    dispatch_async(dispatch_get_main_queue()){
                        //update UI components
                    }

                }
                } //end block
            } //end if let
        }

        HKHealthStore?.executeQuery(stepsQuery)

    }

那么如何将此方法转换为 swift 3 ?

您的代码包含的错误比您描述的要多。我将您的代码复制到 playground 中试图修复它。我不能保证它会工作(我以前从未使用过 HealthKit,但它至少应该编译。

错误 0*

在Swift 3 中,一些类 已重命名。例如 NSCalendarCalendar。函数中的前两行必须更改为:

let calendar = Calendar.current
var interval = DateComponents()

错误 1

要从日期组件中获取日期,您必须使用此函数:

calendar.date(from: anchorComponents)

错误 2:

阅读有关 HKStatisticsCollectionQuery and HKQuantityType 的文档后,我想出了这行代码:

let stepsQuery = HKStatisticsCollectionQuery(quantityType: HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: interval)

HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned) 替换旧代码中的 HKQuantityType

anchorDate: 收到 Date 而不是 DateComponents.

而您传递给 options: 的枚举大小写以 Swift 中的小写字母开头 3.

错误 3*

dateByAddingUnit 已更改。在 Swift 3 中,你使用这个:

calendar.date(byAdding: .day, value: -7, to: endDate)

(同样,枚举大小写现在以小写字母开头。)

错误 4*

enumerateStatistics 也已更改。现在是:

enumerateStatistics(from: startDate!, to: endDate)

错误 5*

HKUnit.countUnit() 已重命名:

let steps = quantity.doubleValue(for: HKUnit.count())

错误 6*

使用多线程的方式已经发生了巨大的变化。

DispatchQueue.main.async {
    //update UI components
}

错误 7*

HKHealthStore?.executeQuery(stepsQuery)有点奇怪。 execute(_:)(在 Swift 3 中命名)不是静态的,只能用于 HKHealthStore 的实例。我用以下行修复了错误消息,但我不确定这是否真的有效。

HKHealthStore().execute(stepsQuery)

*我在 Playground 中使用您的代码时发现了其他错误。

.dateComponents 作为将 Objective-C API 更好地翻译成 swift 的一部分被删除:https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md

尝试

calendar.date(from: DateComponents)

至于你的 healthkit 问题,我怀疑你需要更多类似

的东西
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount

而不是整个 HKQuantityType class。