how to convert a CNPhoneNumber to string in swift4?

六月ゝ 毕业季﹏ 提交于 2020-01-06 11:22:29

问题


I am using this code for getting contact number from contacts app but when I want to show the number in label I get this warning and doesn't work: Cast from 'CNPhoneNumber' to unrelated type 'String' always fails

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    contacts.forEach {(contact) in
        for number in contact.phoneNumbers{
            let phone = number.value
            print(phone)
            numberLabel.text = phone as! String
        }
    }
}

回答1:


TRY :

if let phone = number.value as? CNPhoneNumber {
    print(phone.stringValue)
} else {
   print("number.value not of type CNPhoneNumber")
}

also take a look at CNContact , CNPhoneNumber




回答2:


You can get PhoneNumber value as CNLabeledValue.

for number in contact.phoneNumbers{
    if let number = phoneNumber.value as? CNPhoneNumber, let phoneLabel = phoneNumber.label {
      let phoneLocalizedLabel = CNLabeledValue.localizedStringForLabel(phoneLabel)
          numberLabel.text = "\(phoneLocalizedLabel) : \(number.stringValue)"
    }
}


来源:https://stackoverflow.com/questions/50621917/how-to-convert-a-cnphonenumber-to-string-in-swift4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!