123
123

Reputation: 8951

Value of type HKHealthStore has no type dateOfBirthWithError

I am trying to read data using HealthKit but keeping getting the same issue when I run this code:

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)
}

It gives me the error: Value of type HKHealthStore has no type dateOfBirthWithError

I can't tell why this doesn't work, because I've seen pretty much the exact same code work elsewhere.

Upvotes: 0

Views: 456

Answers (2)

Jorge Casariego
Jorge Casariego

Reputation: 22212

With Swift 2 you can do it in this way:

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)
}

Upvotes: 1

Allan
Allan

Reputation: 7353

In Swift 2.0, methods that take error-out parameters are handled differently than in Swift 1.0 and Objective-C. The method name is just dateOfBirth and it throws an NSError, which you can handle with a try statement.

Upvotes: 0

Related Questions