Не удается преобразовать тип "[String: Any Object]" в ожидаемый тип "String"
Попытка получить строку номера телефона из CNContacts. Я поднимаю контроллер представления выбора контактов, и когда пользователь выбирает несколько контактов, я создаю контроллер представления представления сообщения. Мне нужно создать массив строк для передачи, как получатели сообщения составляют контроллер представления. Ошибка исходит из следующей строки...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)
}
1 ответ
У контакта может быть несколько телефонных номеров, поэтому contact.phoneNumbers возвращает массив CNlabeledValue. Вам нужно два цикла, один для итерации всех контактов, другой для итерации всех чисел. Затем вы должны извлечь номер телефона типа CNPhoneNumber, а затем преобразовать его в строку.
Я сделал некоторые изменения в вашем коде. Надеюсь, поможет.:)
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)
}
}
}