Tuesday 13 May 2014

Get Contacts from Address Book then compare them with database Data and check existance

One of the my project i have to display contacts from contact book and compare them from my database.

For that first you have to read data from the addressbook for that apply the code as below.

-(NSMutableArray*)getaddressBookArray{
    addressBook = nil;
    __block NSMutableArray *arrayOfPeople = nil;
    __block BOOL userDidGrantAddressBookAccess;
    CFErrorRef addressBookError = NULL;
    
    if ( ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined ||
        ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized )
    {
        addressBook = ABAddressBookCreateWithOptions(NULL, &addressBookError);
        
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error){
            userDidGrantAddressBookAccess = granted;
            arrayOfPeople = [(__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook) mutableCopy];

            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    else
    {
        if ( ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
            ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted )
        {
            // Display an error.
        }
    }
    
    return arrayOfPeople;
    

}

Here three case may happen
1> First you have to check whether user has allowed access of contacts or not then array will be empty
2>  Either there are not any records in address book or not then if no contacts available then contacts array remain empty
3> If contacts found then check them from database which you stored internally like this way



In Database I have one table like contacts which has fields like firstName, lastName, number stored which came from sync api i get them in  [self getActiveUsers] Method which get data from database.


Then i make one class for make the contact object .

TKContact.h

@interface TKContact : NSObject {
    NSInteger sectionNumber;
    NSInteger recordID;
    BOOL rowSelected;
    NSString *name;
    NSString *email;
    NSString *tel;
    UIImage *thumbnail;
    NSString *lastName;
    NSString *firstName;
}

@property NSInteger sectionNumber;
@property NSInteger recordID;
@property BOOL rowSelected;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *tel;
@property (nonatomic, retain) UIImage *thumbnail;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *number;
- (NSString*)sorterFirstName;
- (NSString*)sorterLastName;


@end


TKContact.m

#import "TKContact.h"

@implementation TKContact
@synthesize name, email, tel, thumbnail, recordID, sectionNumber, lastName, firstName,number;


- (NSString*)sorterFirstName {
    if (nil != firstName && ![firstName isEqualToString:@""]) {
        return firstName;
    }
    if (nil != lastName && ![lastName isEqualToString:@""]) {
        return lastName;
    }
    if (nil != name && ![name isEqualToString:@""]) {
        return name;
    }
    return nil;
}

- (NSString*)sorterLastName {
    if (nil != lastName && ![lastName isEqualToString:@""]) {
        return lastName;
    }
    if (nil != firstName && ![firstName isEqualToString:@""]) {
        return firstName;
    }
    if (nil != name && ![name isEqualToString:@""]) {
        return name;
    }
    return nil;
}



@end

-(void)checkContacts{
    NSMutableArray *arrNumber = [self getaddressBookArray];
    self.ContactAcccess = FALSE;
    if([arrNumber count]>0){
        self.listContent = [[NSMutableArray alloc] init];
        
        
        NSMutableArray *arr_dbContacts =  [self getActiveUsers];;
        NSMutableArray *contactArray = [[NSMutableArray alloc]init];
        if([arrNumber count]>0){
            for(NSUInteger index = 0; index <= ([arrNumber count]-1); index++){
                
                ABRecordRef currentPerson = (__bridge ABRecordRef)[arrNumber objectAtIndex:index];
                CFStringRef abName = ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty);
                CFStringRef abLastName = ABRecordCopyValue(currentPerson, kABPersonLastNameProperty);
                CFStringRef abFullName = ABRecordCopyCompositeName(currentPerson);
                NSString *currentNumber = @"";
                ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(currentPerson, kABPersonPhoneProperty);
                
                for(CFIndex i = 0; i < ABMultiValueGetCount(phoneNumberProperty); i++) {
                    CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phoneNumberProperty, i);
                    currentNumber = (__bridge NSString *) phoneNumberRef;
                    if(![currentNumber isEqualToString:@""]){
                        currentNumber = [self subtractExceptNumber:currentNumber];
                        if([currentNumber length]>=8){
                            NSString *fullNameString;
                            NSString *firstString = (__bridge NSString *)abName;
                            NSString *lastNameString = (__bridge NSString *)abLastName;
                            
                            if ((__bridge id)abFullName != nil) {
                                fullNameString = (__bridge NSString *)abFullName;
                            } else {
                                if ((__bridge id)abLastName != nil)
                                {
                                    fullNameString = [NSString stringWithFormat:@"%@ %@", firstString, lastNameString];
                                }
                            }
                            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"accountnumber == %@", currentNumber];
                            NSArray *array = [arr_dbContacts filteredArrayUsingPredicate:predicate];
                            if([array count]>0){
                                TKContact *contact = [[TKContact alloc] init];
                                contact.name = fullNameString;
                                contact.number = currentNumber;
                                contact.rowSelected = NO;
                                contact.lastName = (__bridge NSString*)abLastName;
                                contact.firstName = (__bridge NSString*)abName;
                                ABRecordID contactID = ABRecordGetRecordID(currentPerson);
                                ABRecordRef origContactRef = ABAddressBookGetPersonWithRecordID(addressBook, contactID);
                                UIImage *img;
                                if (ABPersonHasImageData(origContactRef)) {
                                    NSData *imgData = (__bridge NSData*)ABPersonCopyImageDataWithFormat(origContactRef, kABPersonImageFormatOriginalSize);
                                    img = [UIImage imageWithData: imgData];
                                    
                                }
                                if(img==nil){
                                    contact.thumbnail = nil;
                                }
                                else{
                                    contact.thumbnail = img;
                                }
                                
                                [contactArray addObject:contact];
                                self.ContactAcccess = TRUE;
                            }
                            
                        }
                    }
                    
                }
                
                
                // Copy the e-mail value into a string.
                //  currentNumber = [_phoneNumbers objectAtIndex:0];
                //  currentNumber = (__bridge NSString *)(ABRecordCopyValue(currentPerson, kABPersonPhoneProperty));
            }
        }
        SEL sorter = ABPersonGetSortOrdering() == kABPersonSortByFirstName ? NSSelectorFromString(@"sorterFirstName") : NSSelectorFromString(@"sorterLastName");
        self.listContent = [[self partitionObjects:contactArray collationStringSelector:sorter] mutableCopy];

    }}


No comments:

Post a Comment