Swift:使用Contacts数据填充TextFields的最简单方法

时间:2016-02-20 12:06:44

标签: ios xcode swift2

我一直在尝试用来自用户联系人的数据填充viewcontroller上的五个空文本字段。 This 似乎是使用“联系人框架”的最全面的讨论和示例,但由于它使用了两个视图控制器,我无法理解在哪里完成的工作。现在,我的代码基本上包括:

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

出现联系人列表,我可以选择一个联系人,然后弹出视图(联系人列表)。当我计算thisContact时 - 所有529个联系人都被计算在内。

请告诉我我做错了什么/正确,以及我需要做些什么来获取这五个键的数据并将其显示在五个TextField中。

1 个答案:

答案 0 :(得分:0)

嗯,事实证明,我一直在思考问题和解决方案。答案很简单:

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)

它可能不完美,但它完美无缺!