简体   繁体   English

如何获取一位联系人的生日-迅捷的iOS 9

[英]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. 我对Swift和iOS相对较新,并且在与通讯录集成时遇到了一些麻烦。 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. 我已经使用了苹果的资源( https://developer.apple.com/library/prerelease/mac/documentation/Contacts/Reference/Contacts_Framework/index.html ),但我不知道如何获取单个联系人的生日。 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. 我正在使用let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("\\(fullnamefield.text!) \\(lastnamefield.text!) \\(suffixfield.text!)"), keysToFetch:[CNContactBirthdayKey]) ,但是此结果在一个我无法理解的数组中。

Your help in finding a specific contact's birthday in swift with the new Contacts Framework would be much appreciated. 非常感谢您在新的联系人框架中快速找到特定联系人生日的帮助。

The array is of type [CNContact] , I believe. 我相信该数组的类型为[CNContact] 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: 您将需要遍历它并检索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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM