Swift4中如何去除获取到的联系人号码中的国家代码?
获取不带国家代码的联系人号码
嘿,我来帮你调整代码,拿到不带国家代码的联系人号码!这里有两种实用方法,你可以根据需求挑选:
方法1:获取纯数字号码(自动剥离所有格式与国家代码)
CNPhoneNumber 自带一个 digits 属性,它会直接返回号码的纯数字部分,自动去掉国家代码、空格、括号这类额外字符。修改你的代码如下:
func fetchContacts(){ let key = [CNContactGivenNameKey, CNContactPhoneNumbersKey] as [CNKeyDescriptor] let request = CNContactFetchRequest(keysToFetch: key) do { try contactStore.enumerateContacts(with: request) { (contact, stoppingPointer) in let name = contact.givenName // 调整号码获取逻辑,拿到不带国家代码的纯数字 let numberWithoutCountryCode = contact.phoneNumbers.first?.value.digits let contactToAppend = ContactStruct(name: name, number: numberWithoutCountryCode) self.contacts.append(contactToAppend) self.queryPhoneNumber() } tableView.reloadData() } catch { print("获取联系人失败:\(error.localizedDescription)") } }
小提醒:我把原来的
try!改成了do-catch,这样能更安全地处理可能的错误,避免程序意外崩溃。
方法2:保留本国格式但去掉国家代码
如果你想要保留号码的本地常用格式(比如美国号码(123) 456-7890,而非纯数字1234567890),可以用CNPhoneNumberFormatter来格式化:
func fetchContacts(){ let key = [CNContactGivenNameKey, CNContactPhoneNumbersKey] as [CNKeyDescriptor] let request = CNContactFetchRequest(keysToFetch: key) // 创建号码格式化器,配置成本国格式 let phoneFormatter = CNPhoneNumberFormatter() phoneFormatter.style = .national phoneFormatter.formattingContext = .standalone do { try contactStore.enumerateContacts(with: request) { (contact, stoppingPointer) in let name = contact.givenName var numberWithoutCountryCode: String? if let phoneNumber = contact.phoneNumbers.first?.value { // 格式化成本国格式,自动移除国家代码 numberWithoutCountryCode = phoneFormatter.string(from: phoneNumber) } let contactToAppend = ContactStruct(name: name, number: numberWithoutCountryCode) self.contacts.append(contactToAppend) self.queryPhoneNumber() } tableView.reloadData() } catch { print("获取联系人失败:\(error.localizedDescription)") } }
两种方法都能帮你去掉国家代码,选哪种就看你需要的号码格式啦~
内容的提问来源于stack exchange,提问作者Sri Vathsav
相关产品推荐
相关产品推荐

