尝试从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)
}
答案 0 :(得分:2)
联系人可以有多个电话号码,因此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)
}
}
}