首页 > 解决方案 > 如何在 swift4 中将 CNPhoneNumber 转换为字符串?

问题描述

我正在使用此代码从联系人应用程序获取联系人号码,但是当我想在标签中显示号码时,我收到此警告并且不起作用:从“CNPhoneNumber”转换为不相关类型“字符串”总是失败

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

标签: swiftcastingcontacts

解决方案


尝试 :

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

也看看CNContactCNPhoneNumber


推荐阅读