ios - 如何获取一个联系人的生日 – swift iOS 9

标签 ios swift ios9 contacts

我对 swift 和 iOS 比较陌生,在与通讯录集成时遇到了一些问题。我使用了苹果的资源(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]),但这会导致我无法理解的数组。

非常感谢您使用新的联系人框架快速帮助查找特定联系人的生日

最佳答案

数组的类型是[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)
}

关于ios - 如何获取一个联系人的生日 – swift iOS 9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35614125/

相关文章:

ios - 如何将 UnsafePointer 映射到另一种类型?

ios - Objective C 为不重复的对象生成随机 ID

ios - 如何将变量的值设置为从 Alamofire 收到的数据?

xcode - 使用 NSURLSession 连接到具有无效证书的服务器(swift2、xcode7、ios9)

ios - 专用 LAN 上的通用链接

ios - 如何将 BFTask 与 Swift 3 结合使用?

iphone - iOS:如何使用网络图像调用系统图像查看器?

swift - Xcode 没有这样的模块 : 'PackageDescription'

arrays - Xcode 在处理文件时卡住

ios - 地址簿在 iOS9 中不工作