owlswipe
owlswipe

Reputation: 19469

How to fetch one contact's birthday–swift iOS 9

I am relatively new to swift and iOS, and I am having some trouble integrating with Contacts. I have used apple's resources (https://developer.apple.com/library/prerelease/mac/documentation/Contacts/Reference/Contacts_Framework/index.html), but I can not figure out how to fetch the birthday of a single contact. I want to take the name a user types in and output the matching contact's birthday to a label. I am using let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("\(fullnamefield.text!) \(lastnamefield.text!) \(suffixfield.text!)"), keysToFetch:[CNContactBirthdayKey]), but this results in an array that I just can not make sense of.

Your help in finding a specific contact's birthday in swift with the new Contacts Framework would be much appreciated.

Upvotes: 1

Views: 2157

Answers (1)

brimstone
brimstone

Reputation: 3400

The array is of type [CNContact], I believe. You'll need to loop through it and retrieve the birthday property, but if you're only finding one contact you can get the first item out of the array and get it's birthday:

let store = CNContactStore()

//This line retrieves all contacts for the current name and gets the birthday and name properties
let contacts:[CNContact] = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("\(fullnamefield.text!) \(lastnamefield.text!) \(suffixfield.text!)"), keysToFetch:[CNContactBirthdayKey, CNContactGivenNameKey])

//Get the first contact in the array of contacts (since you're only looking for 1 you don't need to loop through the contacts)
let contact = contacts[0]

//Check if the birthday field is set
if let bday = contact.birthday?.date as NSDate! {
    //Use the NSDateFormatter to convert their birthday (an NSDate) to a String
    let formatter = NSDateFormatter()
    formatter.timeZone = NSTimeZone(name: "UTC") // You must set the time zone from your default time zone to UTC +0, which is what birthdays in Contacts are set to.
    formatter.dateFormat = "dd/MM/yyyy" //Set the format of the date converter
    let stringDate = formatter.stringFromDate(contact.birthday!.date!)

    //Their birthday as a String:
    print(stringDate)
}

Upvotes: 6

Related Questions