2

I'm trying to retrieve contacts phone numbers to be able to send SMS on behalf of a user. When the number includes the country code (ie starts with +, or 00) I'm fine. However when this is not the case, I'm trying to guess what the country code should be.

// contact is a CNContact with at least one phone number
contact.phoneNumbers[0].value.value(forKey: "countryCode") as? String

returns a country code like us or fr (even if it's not recommended to do so) but I've found it to sometime be inaccurate. My guess is that Apple uses the user's local. It even misclassify numbers with explicit country code. For instance a number 00 54 ... is classified as us while it's from Argentina.

I can also use the user's current local (NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String) and use that to fill missing country codes. But it will obviously misclassify some numbers.

Is there's a better less error prone way?

Community
  • 1
  • 1
Guig
  • 9,891
  • 7
  • 64
  • 126
  • Shouldn't you assume that phone numbers with no country code are in the same country as the user's device? So you goal should be to determine the default country code for the device. – rmaddy Jan 26 '17 at 22:28
  • That'd be the best default I can think off. I guess sometimes I can know that the number format doesn't match the current country, like France is country code + 9 numbers while us is country code + 10 numbers, but that doesn't tell me more about the correct country. I was also wondering why `contact.phoneNumbers[0].value.value(forKey: "countryCode")` is not reliable because that'd ideally be a better guess – Guig Jan 26 '17 at 22:31
  • You definitely can't rely on the phone number format. Many countries use the same number of digits and many countries have more than one valid format (USA can be 7 or 10 for example). And a CNContact won't have a country code if none was ever provided. – rmaddy Jan 26 '17 at 22:36

0 Answers0