Swift - 从ContactPickerViewController

时间:2016-05-21 23:51:09

标签: ios swift contact

我有一个应用程序,其中包含某个人的姓名,电子邮件和地址字段。我使用了CNContactPickerViewController并在我的应用程序标题中声明了委托。点击按钮,我有以下内容:

@IBAction func AddItemFromContactsPressed(sender: AnyObject) {
    let contactPicker = CNContactPickerViewController()
    contactPicker.delegate = self
    contactPicker.displayedPropertyKeys =
        [CNContactEmailAddressesKey, CNContactPhoneNumbersKey]
    self.presentViewController(contactPicker, animated: true, completion: nil)
}

之后,当用户选择联系人时,我有委托方法didSelectContact,并按如下方式使用它:

//DELEGATE METHODS FOR UICONTACT
func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact){
    ItemName.text = contact.givenName + " " + contact.familyName
    if(contact.phoneNumbers.count != 0){
        ItemPhoneContact.text = contact.phoneNumbers[0].value as? String
    }
    if(contact.postalAddresses.count != 0){
        ItemAddress.text = contact.postalAddresses[0].value as? String
    }
}

但是我在拉动postalAddresses时遇到运行时错误。当被淘汰时,我在运行时收到以下警告以获取电话号码:

[Appname ####:####] plugin com.apple.MobileAddressBook.ContactsViewService invalidated

关于发生了什么的任何想法? 提前谢谢!

编辑:我只想指出,获取名称和姓氏非常合适。

2 个答案:

答案 0 :(得分:1)

您正在看到此消息,因为在IOS 9中ABPeoplePickerNavigationController不再有效。

CNContact有新的库/框架,将在IOS 9及以上版本中使用:https://developer.apple.com/library/prerelease/ios/documentation/Contacts/Reference/Contacts_Framework/index.html

答案 1 :(得分:0)

您可以使用CNContactViewController根据名称显示联系人详细信息。

let name = "\(contact.firstName) \(contact.lastName)"
let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: name)
let descriptor = CNContactViewController.descriptorForRequiredKeys()
let contacts: [CNContact]
do {
  contacts = try store.unifiedContacts(matching: predicate, keysToFetch: [descriptor])
  } catch {
    contacts = []
  }

if !contacts.isEmpty {
  guard let contact.first else {return}
  let cvc = CNContactViewController(for: contact)
    cvc.allowsActions = true
    cvc.delegate = self
    cvc.allowsEditing = true
  self.navigationController?.pushViewController(cvc, animated: true)
  }