我正在尝试使用HealthKit读取数据,但在运行此代码时仍然遇到同样的问题:
func readAge() -> ( age:Int?)
{
var error:NSError?
var age:Int?
// 1. Request birthday and calculate age
if let birthDay = healthKitStore.dateOfBirthWithError(&error)
{
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = NSCalendar.currentCalendar().components(.YearCalendarUnit, fromDate: birthDay, toDate: today, options: NSCalendarOptions(0) )
age = differenceComponents.year
}
if error != nil {
print("Error reading Birthday: \(error)")
}
return (age)
}
它给了我错误:Value of type HKHealthStore has no type dateOfBirthWithError
我无法说明为什么这不起作用,因为我已经看到了几乎完全相同的代码在其他地方工作。
答案 0 :(得分:1)
使用Swift 2,你可以这样做:
func readAge() -> ( age:Int?)
{
var error:NSError?
var age:Int?
do {
let birthDay = try healthKitStore.dateOfBirth()
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: birthDay, toDate: today, options: NSCalendarOptions(rawValue: 0))
age = differenceComponents.year
} catch let error as NSError {
print(error.localizedDescription)
}
return (age)
}
答案 1 :(得分:0)
在Swift 2.0中,采用错误输出参数的方法的处理方式与Swift 1.0和Objective-C不同。方法名称仅为dateOfBirth
,它会抛出NSError
,您可以使用try
语句处理该文件。