[英]how to convert a CNPhoneNumber to string in swift4?
我正在使用此代碼從聯系人應用程序獲取聯系號碼,但是當我想在標簽中顯示號碼時,我收到此警告並且不起作用:從“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
}
}
}
嘗試 :
if let phone = number.value as? CNPhoneNumber {
print(phone.stringValue)
} else {
print("number.value not of type CNPhoneNumber")
}
也看看CNContact , CNPhoneNumber
您可以將 PhoneNumber 值設為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)"
}
}
func getContact(){
let numeroinc = self.numero.text!
let contactStore = CNContactStore()
var numeroScodeCuntry = ""
let keys = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactPhoneNumbersKey,
CNContactEmailAddressesKey
] as [Any]
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
for char in UserDefaults.standard.string( forKey: "cc" )!.count ... numeroinc.count-1 {
let index = numeroinc.index(numeroinc.startIndex, offsetBy: char)
numeroScodeCuntry.append(numeroinc[index])
}
numeroScodeCuntry = formattedNumber2(number:numeroScodeCuntry)
print("numeroScodeCuntry", numeroScodeCuntry)
do {
try contactStore.enumerateContacts(with: request){
(contact, stop) in
// Array containing all unified contacts from everywhere
self.contacts.append(contact)
for phoneNumber in contact.phoneNumbers {
if let number = phoneNumber.value as? CNPhoneNumber, let label = phoneNumber.label {
let localizedLabel = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label)
print("\(contact.givenName) \(contact.familyName) tel:\(localizedLabel) -- \(number.stringValue), email: \(contact.emailAddresses)")
print("numeroScodeCuntry",numeroScodeCuntry ,"number.stringValue" , number.stringValue)
let numberContact = self.formattedNumber2(number:number.stringValue)
if (numeroScodeCuntry.isEqualToString(find: numberContact)){
self.numero.text = contact.givenName
print("contact.givenName",contact.givenName)
self.isNumber = false
break
}else{
self.isNumber = true
}
}
}
}
print(self.contacts)
} catch {
print("unable to fetch contacts")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.