【问题标题】:How to fetch one contact's birthday–swift iOS 9如何获取一个联系人的生日——swift iOS 9
【发布时间】:2016-02-24 22:04:54
【问题描述】:

我对 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]),但这会导致我无法理解的数组。

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

【问题讨论】:

    标签: ios swift ios9 contacts


    【解决方案1】:

    我相信这个数组的类型是[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)
    }
    

    【讨论】:

    • 我试过这个并且(谢谢!)但它会在某人生日的前一天输出。我在 Kate Bell 上尝试过,这是模拟器中的默认联系人(她的生日是 1978 年 1 月 20 日),它输出 19/1/1978。有什么想法吗?
    • 没关系!我只需要按照此处的建议设置时区 (stackoverflow.com/a/32046811/5700898)。我已经修改了你的答案。非常感谢!
    • @GabrielJones 请不要要求用户投票。如果他们是新来的,您可以提醒他们accept an answer,但从 John Ramos 的个人资料来看,他们过去曾提出问题并接受了答案,并且知道如何这样做。
    • @JAL 好的,好的,他只是在帮忙!他为我节省了很多小时徒劳无功的工作,所以我认为他应该得到这个支持。
    • @JohnRamos 我很高兴他能帮上忙!并且非常欢迎您根据自己的优点投票和接受答案,但用户不应要求赞成或接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多