Skip to content

Instantly share code, notes, and snippets.

@toblerpwn
Created February 26, 2015 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toblerpwn/e5c9213a8f6c4f4da39a to your computer and use it in GitHub Desktop.
Save toblerpwn/e5c9213a8f6c4f4da39a to your computer and use it in GitHub Desktop.
un-optimized phone number parsing code
/**
* Parses a string using the phone's carrier region (when available, ZZ otherwise).
* This uses the country the sim card in the phone is registered with.
* For example if you have an AT&T sim card but are in Europe, this will parse the
* number using +1 (AT&T is a US Carrier) as the default country code.
* This also works for CDMA phones which don't have a sim card.
*/
- (NBPhoneNumber*)parseWithPhoneCarrierRegion:(NSString*)numberToParse error:(NSError**)error
{
numberToParse = [NBPhoneNumberUtil normalizeNonBreakingSpace:numberToParse];
NSString *defaultRegion = nil;
#if TARGET_OS_IPHONE
defaultRegion = [self countryCodeByCarrier];
#else
defaultRegion = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];
#endif
if ([UNKNOWN_REGION_ isEqualToString:defaultRegion]) {
// get region from device as a failover (e.g. iPad)
NSLocale *currentLocale = [NSLocale currentLocale];
defaultRegion = [currentLocale objectForKey:NSLocaleCountryCode];
}
return [self parse:numberToParse defaultRegion:defaultRegion error:error];
}
#if TARGET_OS_IPHONE
- (NSString *)countryCodeByCarrier
{
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
NSString *isoCode = [[networkInfo subscriberCellularProvider] isoCountryCode];
if (!isoCode) {
isoCode = UNKNOWN_REGION_;
}
return isoCode;
}
+ (NSString*)normalizeNonBreakingSpace:(NSString*)aString
{
return [aString stringByReplacingOccurrencesOfString:NON_BREAKING_SPACE withString:@" "];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment