accessing phone number and display country name or the country code

1k views Asked by At

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.

2

There are 2 answers

0
Om Prakash On

Try this code function you can get all of information would you like.

+(NSArray *)getAllContacts
{
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        accessGranted = granted;
        dispatch_semaphore_signal(sema);
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

}
else { // we're on iOS 5 or older
    accessGranted = YES;
}
if (accessGranted) {
    NSLog(@"Fetching contact info ----> ");
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
    CFIndex nPeople = CFArrayGetCount(allPeople);
    NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
    for (int i = 0; i < nPeople; i++)
    {
        ContactDetailModel *contacts = [[ContactDetailModel alloc] init];  // it is NsObject class. this is contained variables and array which required for get contact information. It is not necessary for you. you can maintain according your requirments. 
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        if((__bridge NSString*)ABRecordCopyCompositeName(person)){
            contacts.compse_name =  (__bridge NSString*)ABRecordCopyCompositeName(person);
            NSLog(@"compse_name = %@",contacts.compse_name);
        }
        if (!contacts.compse_name) {
            contacts.compse_name = @"";
        }

        //get First Name and Last Name

        if((__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty)){
            contacts.first_name = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        }
        if((__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty)){
            contacts.last_name =  (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
        }
        if (!contacts.first_name) {
            contacts.first_name = @"";
        }
        if (!contacts.last_name) {
            contacts.last_name = @"";
        }
        NSLog(@"fname and lname = %@ %@",contacts.first_name,contacts.last_name);


        /// URL
        ABMultiValueRef webpages = ABRecordCopyValue(person, kABPersonURLProperty);
        NSString* homepage;
        // Then iterate thru webpages to get the homepage
        for (CFIndex k=0; k < ABMultiValueGetCount(webpages); k++)
        {
            homepage = (__bridge NSString*)ABMultiValueCopyValueAtIndex(webpages, k);
            NSLog(@"homepage = %@",homepage);

        }
        NSLog(@"URL = %@",homepage); 
        //// get BirthDay
        if((__bridge NSString*)ABRecordCopyValue(person, kABPersonBirthdayProperty)){
            contacts.birthday = (__bridge NSString*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
        }
        if (!contacts.birthday) {
            contacts.birthday = @"";
        }
        //// get Company Name
        if((__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty)){
            contacts.company = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        }
        if (!contacts.company) {
            contacts.company = @"";
        }
        // get contacts picture, if pic doesn't exists, show standart one

        contacts.img_data = (__bridge NSData *)ABPersonCopyImageData(person);

        if (!contacts.img_data) {
            UIImage *image = [UIImage imageNamed:@"[email protected]"];
            NSData *img_data = UIImagePNGRepresentation(image);
            contacts.img_data = img_data;
        }
        //get Phone Numbers
        NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
        ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++) {
            CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
            NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
            NSString * strippedNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [phoneNumber length])];
            [phoneNumbers addObject:strippedNumber];
            //NSLog(@"All numbers %@", phoneNumbers);
        }
        contacts.arrCallIDs = phoneNumbers;
        /// get Addresss
        NSMutableArray *arry_address = [[NSMutableArray alloc] init];
        ABMutableMultiValueRef multiAddress = ABRecordCopyValue(person, kABPersonAddressProperty);
        for(CFIndex i=0; i<ABMultiValueGetCount(multiAddress);i++){
            CFDictionaryRef address = ABMultiValueCopyValueAtIndex(multiAddress, i);
            NSString *street = (NSString*) CFDictionaryGetValue(address, kABPersonAddressStreetKey);
            NSString *city = (NSString*) CFDictionaryGetValue(address, kABPersonAddressCityKey);
            NSString *state = (NSString*) CFDictionaryGetValue(address, kABPersonAddressStateKey);
            NSString *postal = (NSString*) CFDictionaryGetValue(address, kABPersonAddressZIPKey);
            NSString *country = (NSString*) CFDictionaryGetValue(address, kABPersonAddressCountryKey);
            NSString *country_id = (NSString*) CFDictionaryGetValue(address, kABPersonAddressCountryCodeKey);

            NSMutableDictionary *add_field = [[NSMutableDictionary alloc] init];
            [add_field setValue:street forKey:@"street"];
            [add_field setValue:city forKey:@"city"];
            [add_field setValue:state forKey:@"state"];
            [add_field setValue:postal forKey:@"postal"];
            [add_field setValue:country forKey:@"country"];
            [add_field setValue:country_id forKey:@"country_id"];

           // NSLog(@"Address = %@",add_field);
            [arry_address addObject:add_field];
        }
        contacts.arrAddress = arry_address;
        //get Contact email
        NSMutableArray *contactEmails = [NSMutableArray new];
        ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
        for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
            CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
            NSString *contactEmail = (__bridge NSString *)contactEmailRef;
            [contactEmails addObject:contactEmail];
            // NSLog(@"All emails are:%@", contactEmails);
        }
        contacts.arrEmails = contactEmails;
        [items addObject:contacts];
        //NSLog(@"Person is: %@", contacts.firstNames);
        //NSLog(@"Phones are: %@", contacts.numbers);
        //NSLog(@"Email is:%@", contacts.emails);
    }
    return items;
} else {
    NSLog(@"Cannot fetch Contacts :( ");
    return NO;
}
}
4
Vishnu Kumar. S On

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.