我对swift和iOS相对较新,我在使用Contacts时遇到了一些问题。我使用过苹果公司的资源(https://developer.apple.com/library/prerelease/mac/documentation/Contacts/Reference/Contacts_Framework/index.html),但我无法弄清楚如何获取单个联系人的生日。我想获取用户输入的名称,并将匹配的联系人生日输出到标签。我正在使用let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("\(fullnamefield.text!) \(lastnamefield.text!) \(suffixfield.text!)"), keysToFetch:[CNContactBirthdayKey])
,但这会产生一个我无法理解的数组。
非常感谢您使用新的“联系框架”快速找到查找特定联系人生日的帮助。
答案 0 :(得分:6)
我相信数组的类型为[CNContact]
。您需要遍历它并检索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)
}