Monday, 28 September 2015

How To Use AddressBookUI And Conatact Add aand Displaying in IOS/iphone

==>Hare To Add Contact and Get Contact From Addressbook:
==> Some Usefull related AddressBook Implemented And Importing:

#import <UIKit/UIKit.h>

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@import AddressBook;

==> Here Confrim Protocol Of ABPeoplePickerNavigationController:

@interface ViewController : UIViewController <ABPeoplePickerNavigationControllerDelegate>
{
    NSMutableArray *mutArrContactRecords;
}

@property (nonatomic, strong) ABPeoplePickerNavigationController *addressBookController;

@end

========================================================================
#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
==> For User Sise Ask Permssed and Set It :
   
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied || ABAddressBookGetAuthorizationStatus() ==  kABAuthorizationStatusRestricted) {
        NSLog(@"Denied or restricted");
       
        UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot Add Contact" message: @"You must give the app permission to add the contact first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
        [cantAddContactAlert show];
       
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
    {
        NSLog(@"Authorized");
    }else{
//        ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined
        NSLog(@"Not Determinded");
    }
   
   
    ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
       
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!granted){
                //4
                NSLog(@"Just denied");
                UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot Add Contact" message: @"You must give the app permission to add the contact first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
                [cantAddContactAlert show];
                return;
            }
            //5
            NSLog(@"Just authorized");
        });
       
    });
   
    [self getAllRecordsOfAddressBook];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
==> This Method Used Fo Getting All Record From AddressBookUI:


#pragma mark ----------------------
#pragma mark User Define Methods

- (void)getAllRecordsOfAddressBook
{
    ABAddressBookRef aAddBook = ABAddressBookCreateWithOptions(NULL, nil);
   
    NSArray *aArrRecords = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(aAddBook);
   
//    NSLog(@"Records :: %@",aArrRecords);
   
    [aArrRecords enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      
        ABRecordRef aRecPerson = (__bridge ABRecordRef) obj;
       
        NSString *aStrFirstName = (__bridge NSString *) ABRecordCopyValue(aRecPerson, kABPersonFirstNameProperty);
        NSString *aStrLastName = (__bridge NSString *) ABRecordCopyValue(aRecPerson, kABPersonLastNameProperty);
       
        NSLog(@"Name :: %@ %@",aStrFirstName,aStrLastName);
       
        ABMutableMultiValueRef aMultiPhoneNumbers = ABRecordCopyValue(aRecPerson, kABPersonPhoneProperty);
       
        NSString *aStrPhoneNumber;
       
        for (int aIntCnt = 0; aIntCnt < ABMultiValueGetCount(aMultiPhoneNumbers); aIntCnt++) {
           
            CFStringRef aPhoneLable = ABMultiValueCopyLabelAtIndex(aMultiPhoneNumbers, aIntCnt);
            CFStringRef aPhoneValue = ABMultiValueCopyValueAtIndex(aMultiPhoneNumbers, aIntCnt);
           
            if (CFStringCompare(aPhoneLable, kABPersonPhoneMainLabel, 0) == kCFCompareEqualTo) {
                aStrPhoneNumber = (__bridge NSString *)aPhoneValue;
               
                NSLog(@"Name :: %@, %@ :: %@",aStrFirstName, aPhoneLable,aPhoneValue);
            }
           
            CFRelease(aPhoneLable);
            CFRelease(aPhoneValue);
        }
       
        CFRelease(aMultiPhoneNumbers);

       
    }];
   
}
==> Using AddressBookUI to Add Record In AddessBook:

- (IBAction)addRecordClicked:(id)sender {
   
    [self addRecord];
}

==> To Showing And Displaying Recoerd of This Action Clicked in AddressBookUI:-

- (IBAction)showAddressBookClicked:(id)sender {
   
    _addressBookController = [[ABPeoplePickerNavigationController alloc] init];
    [_addressBookController setPeoplePickerDelegate:self];
    [self presentViewController:_addressBookController animated:YES completion:nil];
}

- (void)addRecord
{
    NSString *aStrFirstName = @"ILDC";
    NSString *aStrLastName = @"IndiaNIC";
    NSString *aStrPhNumber = @"8888888888";
   
    NSData *aDtImage = UIImageJPEGRepresentation([UIImage imageNamed:@"car.jpg"], 1.0);
   
    ABAddressBookRef aAddBookRef = ABAddressBookCreateWithOptions(NULL, nil);
    ABRecordRef aRecRef = ABPersonCreate();
   
    ABRecordSetValue(aRecRef, kABPersonFirstNameProperty, (__bridge CFStringRef)aStrFirstName, nil);
    ABRecordSetValue(aRecRef, kABPersonLastNameProperty, (__bridge CFStringRef)aStrLastName, nil);
   
    ABMutableMultiValueRef aPhoneNmbs = ABMultiValueCreateMutable(kABMultiStringPropertyType);
   
    ABMultiValueAddValueAndLabel(aPhoneNmbs, (__bridge CFStringRef)aStrPhNumber, kABPersonPhoneMainLabel, NULL);
   
    ABRecordSetValue(aRecRef, kABPersonPhoneProperty, aPhoneNmbs, nil);
   
    // To set Image
   
    ABPersonSetImageData(aRecRef, (__bridge CFDataRef)aDtImage, nil);
   
    NSArray *aArrRecords = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(aAddBookRef);
    BOOL aBoolExists = NO;
   
    __block BOOL ablockBoolExits = aBoolExists;
   
    for (int aIntCnt = 0; aIntCnt < aArrRecords.count; aIntCnt++) {
       
        ABRecordRef aRecPerson = (__bridge ABRecordRef) [aArrRecords objectAtIndex:aIntCnt];
       
        if (CFStringCompare(ABRecordCopyCompositeName(aRecPerson),
                            ABRecordCopyCompositeName(aRecRef), 0) == kCFCompareEqualTo){
            //The contact already exists!
            NSLog(@"//The contact already exists!");
            ablockBoolExits = YES;
            break;
        }
    }
   
    if (aBoolExists) {
        return;
    }
   
   
    CFRelease(aPhoneNmbs);
    CFRelease(aRecRef);
    CFRelease(aAddBookRef);
   
    [self getAllRecordsOfAddressBook];
   
}


#pragma mark ----------------------
#pragma mark ABPeople Picker Address Book Delegate Methods

-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [_addressBookController dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
    NSMutableDictionary *contactInfoDict = [[NSMutableDictionary alloc]
                                            initWithObjects:@[@"", @"", @"", @"", @"", @"", @"", @"", @""]
                                            forKeys:@[@"firstName", @"lastName", @"mobileNumber", @"homeNumber", @"homeEmail", @"workEmail", @"address", @"zipCode", @"city"]];
   
    CFTypeRef generalObj;
    generalObj = ABRecordCopyValue(person, kABPersonFirstNameProperty);
   
    if (generalObj) {
        [contactInfoDict setObject:(__bridge NSString *)generalObj forKey:@"firstName"];
       
        CFRelease(generalObj);
    }
   
    // Phone Numbers
   
    ABMutableMultiValueRef aMultiPhoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
   
    for (int i=0; i < ABMultiValueGetCount(aMultiPhoneNumbers); i++) {
       
        CFStringRef currentPhoneLabel = ABMultiValueCopyLabelAtIndex(aMultiPhoneNumbers, i);
        CFStringRef currentPhoneValue = ABMultiValueCopyValueAtIndex(aMultiPhoneNumbers, i);
       
        if (CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"mobileNumber"];
        }
       
        if (CFStringCompare(currentPhoneLabel, kABHomeLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"homeNumber"];
        }
       
        CFRelease(currentPhoneLabel);
        CFRelease(currentPhoneValue);
    }
    CFRelease(aMultiPhoneNumbers);
   
   
    // Email
   
    ABMultiValueRef emailsRef = ABRecordCopyValue(person, kABPersonEmailProperty);
    for (int i=0; i<ABMultiValueGetCount(emailsRef); i++) {
        CFStringRef currentEmailLabel = ABMultiValueCopyLabelAtIndex(emailsRef, i);
        CFStringRef currentEmailValue = ABMultiValueCopyValueAtIndex(emailsRef, i);
       
        if (CFStringCompare(currentEmailLabel, kABHomeLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"homeEmail"];
        }
       
        if (CFStringCompare(currentEmailLabel, kABWorkLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"workEmail"];
        }
       
        CFRelease(currentEmailLabel);
        CFRelease(currentEmailValue);
    }
    CFRelease(emailsRef);
   
   
    // Addresss
   
    ABMultiValueRef addressRef = ABRecordCopyValue(person, kABPersonAddressProperty);
   
    if (ABMultiValueGetCount(addressRef) > 0) {
        NSDictionary *addressDict = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(addressRef, 0);
       
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressStreetKey] forKey:@"address"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressZIPKey] forKey:@"zipCode"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressCityKey] forKey:@"city"];
    }
    CFRelease(addressRef);
   
   
    // If Image exists
   
    if (ABPersonHasImageData(person)) {
        NSData *contactImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
       
        [contactInfoDict setObject:contactImageData forKey:@"image"];
    }
   
    NSLog(@"Person :: %@",contactInfoDict);
   
    //    if (mutArrContactRecords == nil) {
    //        mutArrContactRecords = [[NSMutableArray alloc] init];
    //    }
    //    [mutArrContactRecords addObject:contactInfoDict];
   
}

-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
   
    NSMutableDictionary *contactInfoDict = [[NSMutableDictionary alloc]
                                            initWithObjects:@[@"", @"", @"", @"", @"", @"", @"", @"", @""]
                                            forKeys:@[@"firstName", @"lastName", @"mobileNumber", @"homeNumber", @"homeEmail", @"workEmail", @"address", @"zipCode", @"city"]];
   
    CFTypeRef generalObj;
    generalObj = ABRecordCopyValue(person, kABPersonFirstNameProperty);
   
    if (generalObj) {
        [contactInfoDict setObject:(__bridge NSString *)generalObj forKey:@"firstName"];
       
        CFRelease(generalObj);
    }
   
    // Phone Numbers
   
    ABMutableMultiValueRef aMultiPhoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
   
    for (int i=0; i < ABMultiValueGetCount(aMultiPhoneNumbers); i++) {
       
        CFStringRef currentPhoneLabel = ABMultiValueCopyLabelAtIndex(aMultiPhoneNumbers, i);
        CFStringRef currentPhoneValue = ABMultiValueCopyValueAtIndex(aMultiPhoneNumbers, i);
       
        if (CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"mobileNumber"];
        }
       
        if (CFStringCompare(currentPhoneLabel, kABHomeLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"homeNumber"];
        }
       
        CFRelease(currentPhoneLabel);
        CFRelease(currentPhoneValue);
    }
    CFRelease(aMultiPhoneNumbers);
   
   
    // Email
   
    ABMultiValueRef emailsRef = ABRecordCopyValue(person, kABPersonEmailProperty);
    for (int i=0; i<ABMultiValueGetCount(emailsRef); i++) {
        CFStringRef currentEmailLabel = ABMultiValueCopyLabelAtIndex(emailsRef, i);
        CFStringRef currentEmailValue = ABMultiValueCopyValueAtIndex(emailsRef, i);
       
        if (CFStringCompare(currentEmailLabel, kABHomeLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"homeEmail"];
        }
       
        if (CFStringCompare(currentEmailLabel, kABWorkLabel, 0) == kCFCompareEqualTo) {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"workEmail"];
        }
       
        CFRelease(currentEmailLabel);
        CFRelease(currentEmailValue);
    }
    CFRelease(emailsRef);
   
   
    // Addresss
   
    ABMultiValueRef addressRef = ABRecordCopyValue(person, kABPersonAddressProperty);
   
    if (ABMultiValueGetCount(addressRef) > 0) {
        NSDictionary *addressDict = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(addressRef, 0);
       
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressStreetKey] forKey:@"address"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressZIPKey] forKey:@"zipCode"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressCityKey] forKey:@"city"];
    }
    CFRelease(addressRef);
   
   
    // If Image exists
   
    if (ABPersonHasImageData(person)) {
        NSData *contactImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
       
        [contactInfoDict setObject:contactImageData forKey:@"image"];
    }
   
    NSLog(@"Person :: %@",contactInfoDict);
   
//    if (mutArrContactRecords == nil) {
//        mutArrContactRecords = [[NSMutableArray alloc] init];
//    }
//    [mutArrContactRecords addObject:contactInfoDict];
   
    return NO;
}


@end