无法将类型“[String: Any Object]”转换为预期类型 'String'

Cannot convert type '[String: Any Object]' to expected type 'String'

正在尝试从 CNContacts 中获取 phone 号码字符串。我拉出一个联系人选择器视图控制器,当用户选择多个联系人时,我创建一个消息撰写视图控制器。我需要创建一个字符串数组,作为消息的接收者传递给撰写视图控制器。错误来自以下行...contactsPhoneNumber.append(phoneNumber)

func AddFriendTapped() {
    let contactPickerViewController = CNContactPickerViewController()
    contactPickerViewController.delegate = self
    presentViewController(contactPickerViewController, animated: true, completion: nil)
}


func contactPicker(picker: CNContactPickerViewController,didSelectContacts contacts: [CNContact]) {

    //check if phone can send texts, if so, continue
    if !MFMessageComposeViewController.canSendText(){

        let composeVC = MFMessageComposeViewController()
        composeVC.messageComposeDelegate = self

        //must get phone number strings from CNContact
        let phoneNumberKey = [CNContactPhoneNumbersKey]
        for contact in contacts {
            var phoneNumber = contact.dictionaryWithValuesForKeys(phoneNumberKey)
            contactsPhoneNumber.append(phoneNumber)
        }

        composeVC.recipients = contactsPhoneNumber
        composeVC.body = "Hi, test message"

        // Present the view controller modally.
        dismissViewControllerAnimated(true) {
            self.presentViewController(composeVC, animated: true, completion: nil)
        }

    }

}

func messageComposeViewController(controller: MFMessageComposeViewController,
                                  didFinishWithResult result: MessageComposeResult) {
    // Check the result or perform other tasks.

    // Dismiss the mail compose view controller.
    controller.dismissViewControllerAnimated(true, completion: nil)
}

一个联系人可以有多个 phone 号码,因此 contact.phoneNumbers returns 一个 CNlabeledValue 数组。您需要两个循环,一个循环遍历所有联系人,另一个循环遍历所有数字。然后你必须提取CNPhoneNumber类型的phone号码,然后将其转换为字符串。

我对你的代码做了一些修改。希望能帮助到你。 :)

func contactPicker(picker: CNContactPickerViewController,didSelectContacts contacts: [CNContact]) {

    //check if phone can send texts, if so, continue
    if !MFMessageComposeViewController.canSendText(){

        let composeVC = MFMessageComposeViewController()
        composeVC.messageComposeDelegate = self

        //must get phone number strings from CNContact

        //let phoneNumberKey = [CNContactPhoneNumbersKey]


        for contact in contacts {
            let contactNumberArray = contact.phoneNumbers
            for contactNumber in contactNumberArray{
                let number = contactNumber.value as! CNPhoneNumber
                contactsPhoneNumber.append(number.stringValue)
            }
        }


        composeVC.recipients = contactsPhoneNumber
        composeVC.body = "Hi, test message"

        // Present the view controller modally.
        dismissViewControllerAnimated(true) {
            self.presentViewController(composeVC, animated: true, completion: nil)
        }

    }

}