Search code examples
iosobjective-cuitableviewaddressbook

I want to fetch contact list from phone on tableview in ios?


I have written this code

contactlistvc.h

#import <UIKit/UIKit.h>

@interface ContactListVc : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *contactTable;
    NSMutableArray *tableData;

}
@property (strong, nonatomic) IBOutlet UITableView *contactTable;
@property (nonatomic, strong) NSMutableArray *tableData;

contactlistvc.m

#import "ContactListVc.h"
#import <AddressBook/AddressBook.h>
#import "Person.h"

@interface ContactListVc ()

@end

@implementation ContactListVc
@synthesize tableData,contactTable;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.backgroundColor = [UIColor blueColor];
    tableData = [[NSMutableArray alloc]init];
    contactTable = [[UITableView alloc]init];
    contactTable.dataSource = self;
    contactTable.delegate = self;
    [self getPersonOutOfAddressBook];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    Person *person = [self.tableData objectAtIndex:indexPath.row];
    cell.textLabel.text = person.fullName;


    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)getPersonOutOfAddressBook
{
    //1
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    if (addressBook != nil) {
        NSLog(@"Succesful.");
        NSLog(@"tabledata %@",tableData);

        //2
        NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);

        //3
        NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
        {
            Person *person = [[Person alloc] init];
            ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];

            //4
            NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
                                                                                  kABPersonFirstNameProperty);
            NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
            NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

            person.firstName = firstName; person.lastName = lastName;
            person.fullName = fullName;

            //email
            //5
            ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);

            //6
            NSUInteger j = 0;
            for (j = 0; j < ABMultiValueGetCount(emails); j++) {
                NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
                if (j == 0) {
                    person.homeEmail = email;
                    NSLog(@"person.homeEmail = %@ ", person.homeEmail);
                }
                else if (j==1) person.workEmail = email;
            }

            //7
            [self.tableData addObject:person];
        }

        //8
        CFRelease(addressBook);
    } else {
        //9
        NSLog(@"Error reading Address Book");
    }
}

But i am not getting the contact list. only successfull is coming on console window. I am having 3 tab bar on one tab of contact i want to show the contact list of phone in tableview. Plz help me , thanks.


Solution

  • You need to first get permission to access the native DB...

    - (void)requestPermissionForContactsAccessAndFetch
    {
    
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    
        if (status != kABAuthorizationStatusAuthorized && status != kABAuthorizationStatusNotDetermined) {
        // tell user to enable contacts in privacy settings
            NSLog(@"You previously denied access: You must enable access to contacts in settings");
    
            return;
        }
    
        CFErrorRef error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
        if (!addressBook) {
            NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error));
            return;
        }
    
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
           if (error) {
            NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error));
        }
    
        if (granted) {
            [self getContactsFromAddressBook:addressBook];
        } else {
            // tell user to enable contacts in privacy settings
            NSLog(@"You just denied access: You must enable access to contacts in settings");
        }
    
        CFRelease(addressBook);
    });
    }
    

    Then you can get all contacts in an array...

    - (NSMutableArray*)getContactsFromAddressBook:(ABAddressBookRef)addressBook
       {
    NSArray *allData = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
        NSInteger contactCount = [allData count];
    
    for (int i = 0; i < contactCount; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex((__bridge CFArrayRef)allData, i);
    
        NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (firstName) {
            dictionary[@"firstName"] = firstName;
        }
        if (lastName) {
            dictionary[@"lastName"]  = lastName;
        }
    
        ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        CFIndex phoneNumberCount = ABMultiValueGetCount(phones);
    
        if (phoneNumberCount > 0) {
            NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, 0));
            dictionary[@"phone"] = phone;
        }
    
        // or if you wanted to iterate through all of them, you could do something like this...        
        // for (int j = 0; j < phoneNumberCount; j++) {
        //      NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, j));
         // }
    
        if (phones) {
            CFRelease(phones);
        }
    
        [arrOfContacts addObject:dictionary];
    }
    }