簡體   English   中英

如何獲取一位聯系人的生日-迅捷的iOS 9

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

我對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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM