I've been trying to populate five empty textfields on a viewcontroller with data from the user's contacts. This seems to be the most comprehensive discussion and example of working with the Contacts Framework, but because it's using two viewcontrollers, I just can't get my head wrapped around what gets done where. Right now, my code basically consists of:
var thisContact = [CNContact]()
@IBAction func actionBtn_AddClientsFromContactsBtn(sender: AnyObject) {
let contactPickerViewController = CNContactPickerViewController()
contactPickerViewController.delegate = self
presentViewController(contactPickerViewController, animated: true, completion: nil)
}
func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
didFetchContacts([contact])
//The magic should be happening here, right???
navigationController?.popViewControllerAnimated(true)
}
func didFetchContacts(contacts: [CNContact]) {
for contact in contacts {
self.thisContact.append(contact)
}
}
The Contacts list appears, and I'm able to select a contact whereafter the view (Contacts list) pops. When I do a count of thisContact
- all 529 contacts are counted.
Please enlighten me on what I'm doing wrong/right, and what I need to do to get those five keys' data and get it displayed in the five TextFields.
Well, as it turns out, I've been overthinking the problem and the solution. the answer was quite easy:
func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
let myContact = contact
let myContactFirstName = myContact.givenName
let myContactLastName = myContact.familyName
let myContactJobTitle = myContact.jobTitle
outletTextField_UserClientFirstName.text = myContactFirstName.uppercaseString
outletTextField_UserClientLastName.text = myContactLastName.uppercaseString
outletTextField_UserClientJobTitle.text = myContactJobTitle
// Set the contact's work email address.
var myContactWorkEmailAddress: String!
for workEmailAddress in contact.emailAddresses {
if workEmailAddress.label == CNLabelWork {
myContactWorkEmailAddress = workEmailAddress.value as! String
outletTextField_UserClientWorkEmailAddress.text = myContactWorkEmailAddress
break
}
}
// Set the contact's work phone number.
var myContactWorkPhoneNumber: String!
var myContactWorkPhoneNumberArray = [String]()
for mainPhone in contact.phoneNumbers {
if mainPhone.label == CNLabelPhoneNumberMain {
let mainPhoneValue = mainPhone.value as! CNPhoneNumber
myContactWorkPhoneNumberArray.append(mainPhoneValue.stringValue)
myContactWorkPhoneNumber = myContactWorkPhoneNumberArray[0]
outletTextField_UserClientMobilePhoneNumber.text = myContactWorkPhoneNumber
break
}
}
navigationController?.popViewControllerAnimated(true)
It might not be perfect, but it works perfectly!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.