I want to get the country code and phone number from CNContact on iOS 9. I tried many things but couldn\'t find a way. The best result I achieved is printing:
Objective-C:
[number.value valueForKey:@"countryCode"]
Swift:
number.value.valueForKey("countryCode") as? String
valueForKey
is not private, and your app will not get rejected.
/* Get only first mobile number */
let MobNumVar = (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String
print(MobNumVar)
/* Get all mobile number */
for ContctNumVar: CNLabeledValue in contact.phoneNumbers
{
let MobNumVar = (ContctNumVar.value as! CNPhoneNumber).valueForKey("digits") as? String
print(MobNumVar!)
}
/* Get mobile number with mobile country code */
for ContctNumVar: CNLabeledValue in contact.phoneNumbers
{
let FulMobNumVar = ContctNumVar.value as! CNPhoneNumber
let MccNamVar = FulMobNumVar.valueForKey("countryCode") as? String
let MobNumVar = FulMobNumVar.valueForKey("digits") as? String
print(MccNamVar!)
print(MobNumVar!)
}
To get Country code you can use this:
(contact.phoneNumbers[0].value ).value(forKey: "countryCode") as! String
in for loop, and key; "digits" is to get full phone number.
Unfortunately you can't get them since they are private.
let numberValue = number.value
let countryCode = numberValue.valueForKey("countryCode") as? String
let digits = numberValue.valueForKey("digits") as? String
This works but if you do something in this lines your app will most likely be rejected.
You can see all the nice stuff you could use here.
If you don't plan on uploading your app to the store the solution above is OK, otherwise I'd stick with some kind of regex knowing it can break in the future:
countryCode=(\w{2}),.*digits=(.+)>$
They two members can be accessed via valueForKey
:
let countryCode = number.valueForKey("countryCode") as? String
let digits = number.valueForKey("digits") as? String
Please note that due to the fact that these two fields are part of a private API, there's no guarantee that in the future versions of the Contacts
framework they won't be removed/replaced.