You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:18