I accessing contacts and sending it to server, my question is do I have any possibility of detecting which country contact belongs to? Thank you.
accessing phone number and display country name or the country code
1k views Asked by krishna AtThere are 2 answers
Follow the steps below.
1 : Fetch the phone numbers from device.
2 : You need to find the country code from the phone number. Phone numbers can be saved in the device in different formats. International format, local format, with country code, without country code etc. So you need to consider all these cases to split the country code from the phone number. The following code may help you to get the country code from the phone number.
- (NSString *)getDiallingCodeFromPhoneNumber:(NSString *)phoneNumber
{
NSString *countryCode = @"not found";
NSString *code;
NSString *dialledNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:@"-() "]]
componentsJoinedByString:@""];
NSString *interNationalCode = [dialledNumber substringToIndex:2];
NSArray *allCodes = [self.diallingCodesDictionary allValues];
int idx;
if([dialledNumber hasPrefix:@"+"])
{
dialledNumber = [dialledNumber substringFromIndex:1];
}
else if([interNationalCode isEqualToString:@"00"])
{
dialledNumber = [dialledNumber substringFromIndex:2];
}
for (idx = 1 ; idx < dialledNumber.length; idx++) {
code = [dialledNumber substringToIndex:idx];
if([allCodes containsObject:code])
{
countryCode = code;
break;
}
}
return countryCode;
}
3 : You will get the list of country codes and country name from internet. Add it as a plist in your bundle. (I took this plist from a third part, HMDiallingCode
)
4 : Now you will get the country name corresponding to your country code from that plist.
5 : If you got countryCode = not found, it means that the phone number is not saved with country code. This makes it clear that, that particular phone number is a local number. So in this case you can select the country name from NSLocale
.
Try this code function you can get all of information would you like.