我可以使用 iOS9 联系人框架来获取格式化的 phone 号码吗?

Can I use iOS9 Contacts Framework to get a formatted phone number?

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

"17185555555"
"+17185555555"
"+447788888888"

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

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

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

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

我知道我可以使用 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

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

来自 我知道我可以从 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)
}

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

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

我的回答提出了另一个库

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

你可以这样使用:

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