【问题标题】:Can I use iOS9 Contacts Framework to get a formatted phone number?我可以使用 iOS9 联系人框架来获取格式化的电话号码吗?
【发布时间】:2017-01-11 00:35:48
【问题描述】:

我希望能够以标准方式存储电话号码,例如只是数字(可能带有国家代码的“+”),类似于这些示例......

"17185555555"
"+17185555555"
"+447788888888"

...但我希望能够以正确格式的方式向用户显示它,例如

"1 (718) 555-5555"
"+1 (718) 555-5555"
"+44 (7788) 888888"

...无需依赖 CNContactViewController 对其进行格式化。

显然,仅针对美国/加拿大号码执行此操作会很容易 - 这只是一种标准格式 - 但我希望它是通用的,以便它适用于来自任何国家/地区的号码。我知道this 问题仅针对美国/加拿大号码给出了答案。

我知道我可以使用 CNContactViewController 以正确的格式显示数字,例如

let newContact = CNMutableContact()
newContact.givenName = "John"
newContact.familyName = "Smith"
newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue:"17185555555"))]
let contactView = CNContactViewController(forContact: newContact)
self.presentViewController(contactView, animated: true, completion: nil)

这将在屏幕上显示正确格式的数字,即

1 (718) 555-5555

...所以我知道框架中的某些东西可以做到这一点。 (此方法适用于其他国家/地区电话号码格式,只要您在号码前加上正确的国家/地区代码 - 例如“+44...”)

来自various other questions 我知道我可以从 CNContact 中获取原始数字和国家/地区代码,例如(按照上面的例子)

for pNumber: CNLabeledValue in newContact.phoneNumbers {
    let value  = pNumber.value as! CNPhoneNumber
    let cc = value.valueForKey("countryCode") as? String
    let digits = value.valueForKey("digits") as? String
    print("cc:" + cc + ", " + digits)
}

...但这只会再次显示未格式化的字符串-在这种情况下不是我要查找的内容。

非常感谢任何帮助或其他推荐的方法!

【问题讨论】:

  • 我看到了那个问题(现在将链接到它),但我相信我说的对,它仅适用于美国/加拿大格式的数字,这不是我想要的。跨度>
  • 我不知道你所说的“那个”是什么意思。那里的答案显示了提供可识别区域设置的电话号码格式化程序需要什么。

标签: ios swift contacts


【解决方案1】:

我的回答提出了另一个库

您可以使用this lib 格式化您的号码。

你可以这样使用:

let phoneNumber: NBPhoneNumber = try phoneUtil.parse("17185555555", defaultRegion: yourRegion)
let formattedString: String = try phoneUtil.format(phoneNumber, numberFormat: .E164)

【讨论】:

  • 效果很好 - 谢谢。可能总比尝试依赖联系人框架更好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 2020-06-05
相关资源
最近更新 更多