Saturday, 17 June 2017

// Contact BOOK with CNContacts

//  ContactVc.m
//
//Add two framework Contacts.framwork and ContactsUI.framwork
//  Add InfoPlist ===> Privacy - Contacts Usage Description
//          create the outlet of tableView ===>  @property (strong, nonatomic) IBOutlet UITableView *tableVw;


#import "ContactVc.h"
@import Contacts;
#import <Contacts/Contacts.h>
@interface ContactVc ()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *_contacts;
    NSMutableArray *contactsArray;
   
}

@end

@implementation ContactVc

- (void)viewDidLoad {
    [super viewDidLoad];
    _tableVw.delegate=self;
    _tableVw.dataSource=self;
//    NameArr =[[NSMutableArray alloc]init];
//    phNo =[[NSMutableArray alloc]init];
//    imageArr =[[NSMutableArray alloc]init];
    [self contactsDetailsFromAddressBookCNContacts];
   // [self contactList];
   // [self getPhList];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return contactsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[_tableVw dequeueReusableCellWithIdentifier:@"cellid"];
    UIImageView *imagVw=[[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 44, 44)];
    imagVw.layer.cornerRadius=imagVw.frame.size.height/2;
    imagVw.image=[[contactsArray valueForKey:@"userImage"]objectAtIndex:indexPath.row];
    [cell addSubview:imagVw];
    UILabel *lblName =[[UILabel alloc]initWithFrame:CGRectMake(imagVw.frame.size.width+20, 0, cell.frame.size.width-imagVw.frame.size.width, 22)];
    
    lblName.text=[[contactsArray valueForKey:@"fullName"]objectAtIndex:indexPath.row];
    UILabel *lblPhNo =[[UILabel alloc]initWithFrame:CGRectMake(imagVw.frame.size.width+20, 25, cell.frame.size.width-imagVw.frame.size.width, 18)];
   lblPhNo.text= [[contactsArray valueForKey:@"PhoneNumbers"]objectAtIndex:indexPath.row];
    [cell addSubview:lblName];
    [cell addSubview:lblPhNo];
    cell.backgroundColor=[UIColor colorWithRed:0.91 green:1.00 blue:1.00 alpha:1.0];
    //cell.imageView.image=[imageArr objectAtIndex:indexPath.row];
       // cell.textLabel.text=[NameArr objectAtIndex:indexPath.row];
       // cell.detailTextLabel.text=[phNo objectAtIndex:indexPath.row];
    return cell;
}
-(void)contactsDetailsFromAddressBookCNContacts{
    //ios 9+
    contactsArray =[[NSMutableArray alloc]init];
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted == YES) {
            //keys with fetching properties
            NSArray *keys = @[CNContactBirthdayKey,CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactEmailAddressesKey];
            NSString *containerId = store.defaultContainerIdentifier;
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
            if (error) {
                NSLog(@"error fetching contacts %@", error);
            } else {
                NSString *phone;
                NSString *fullName;
                NSString *firstName;
                NSString *lastName;
                UIImage *profileImage;
                NSDateComponents *birthDayComponent;
                NSMutableArray *contactNumbersArray;
                NSString *birthDayStr;
                NSMutableArray *emailArray;
                NSString* email = @"";
                for (CNContact *contact in cnContacts) {
                    // copy data to my custom Contacts class.
                    firstName = contact.givenName;
                    lastName = contact.familyName;
               
                    if (lastName == nil) {
                        fullName=[NSString stringWithFormat:@"%@",firstName];
                    }else if (firstName == nil){
                        fullName=[NSString stringWithFormat:@"%@",lastName];
                    }
                    else{
                        fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                    }
                    UIImage *image = [UIImage imageWithData:contact.imageData];
                    if (image != nil) {
                        profileImage = image;
                    }else{
                        profileImage = [UIImage imageNamed:@"placeholder.png"];
                    }
                    for (CNLabeledValue *label in contact.phoneNumbers) {
                        phone = [label.value stringValue];
                        if ([phone length] > 0) {
                            [contactNumbersArray addObject:phone];
                        }
                    }
            NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
                    NSLog(@"ResponseDict: %@",personDict);
                    [contactsArray addObject:personDict];
                    NSLog(@"contactsArray%@", contactsArray);
                   
                
                  [self.tableVw reloadData];
                    
                }

            }
        }
    }];
}
-(BOOL)shouldAutorotate{ return NO; }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end

Monday, 22 May 2017

Get Contact Address Book

//
//  ContactVC.m
//  QuickBloxDemo
//

////  AddressBook framework Add and Add Plist file name.Privacy Contact description
//  Raman Mann



#import "ContactVC.h"
#import <AddressBook/AddressBook.h>
@interface ContactVC ()<UITableViewDelegate,UITableViewDataSource>
    {
        NSMutableArray * arrayContactData;
        NSMutableArray * nameArray;
        NSMutableArray *addressBookNumList;
        NSArray *sortedArr;
    }
@end
@implementation ContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    self.navigationItem.title = @"Contact";
    _tblvw.delegate =self;
    _tblvw.dataSource=self;
    addressBookNumList =[[NSMutableArray alloc]init];
    [self getContacts];
   
    NSLog(@"%@",[QBChat instance].contactList.contacts);
    NSLog(@"%@",[QBChat instance].contactList.pendingApproval);
   
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)getContacts
{
   
    arrayContactData =[[NSMutableArray alloc]init];
    // NSString * phoneStr ;
    NSString *firstName;
    nameArray =[[NSMutableArray alloc]init];
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
    {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
                                                 {
                                                    
                                                 });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
       
    {
        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
        CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
       
        for(int i = 0; i < numberOfPeople; i++)
        {
            ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
           
            firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
            NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
           
            if (lastName==NULL)
            {
                lastName =@"";
            }
            NSString * name =[NSString stringWithFormat:@"%@ %@",firstName,lastName];
            //NSLog(@"%@",name);
           
            ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
            [[UIDevice currentDevice] name];
           
            for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++)
            {
                NSString * phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
                //NSLog(@"%@",phoneNumber);
                // NSString * phoneNumDecimalsOnly = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
                if ([name isEqualToString:@"(null)"])
                {
                    name = phoneNumber;
                }
                [nameArray addObject:name];
               
                [addressBookNumList addObject:phoneNumber];
               
               
                NSMutableDictionary * contactDic = [[NSMutableDictionary alloc]init];
                [contactDic setObject:name forKey:@"name"];
                [contactDic setObject:phoneNumber forKey:@"phoneNumber"];
                [arrayContactData addObject:contactDic];
            }
           
        }
       
        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        sortedArr = [arrayContactData sortedArrayUsingDescriptors:@[sd1]];
       
        //NSLog(@"%@",sortedArr);
       
        NSString *     str = [NSString stringWithFormat:@"%@",[addressBookNumList firstObject]];
       
        for (int iterator = 1; iterator < addressBookNumList.count; iterator++)
        {
            str = [NSString stringWithFormat:@"%@,%@",str,addressBookNumList[iterator]];
        }
    }
    else
    {
        // Send an alert telling user to change privacy setting in settings app
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return  sortedArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellid"] ;
   
   
    //[[arrayContactData valueForKey:@"name"]objectAtIndex:indexPath.row];
    cell.textLabel.text =[[sortedArr valueForKey:@"name"]objectAtIndex:indexPath.row];
   
    //NSLog(@"%@",[[sortedArr valueForKey:@"name"]objectAtIndex:indexPath.row]);
    NSLog(@"%@",sortedArr);
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0f];
    cell.detailTextLabel.text = [[sortedArr valueForKey:@"phoneNumber"]objectAtIndex:indexPath.row];
   
    return cell;
}

@end