Mitesh Varu
Mitesh Varu

Reputation: 246

How to Get Duplicate Contact list iOS and merge or delete Contact?

I Want to Delete Duplicate or Merge duplicate Contact Can anyOne Provide me Sample Code for it !!!!! I want to get the List of Duplicate Contact in tableview and merge them or delete them

Upvotes: 0

Views: 1478

Answers (1)

user3182143
user3182143

Reputation: 9609

I created sample project for you.I got the solution.it works perfectly.

Addressbook framework is deprecated from iOS 9.So we need to use Contact framework.

We must import Contact framework

Next in plist If you want to access contacts,you have to get authorization permission so you need to add Privacy - Contacts Usage Description

Key is Privacy - Contacts Usage Description
Type is string
Value is contact (whatever you want add here as string)

ViewController.h

#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h> 

@interface ViewController :  UIViewController<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tblViewContact;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *arrData;
    NSMutableArray *arraySearchContactData;
}

@end

@implementation ViewController

@synthesize tblViewContact;

- (void)viewDidLoad 
{
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.
   arrData = [[NSMutableArray alloc]init];
   [self getContact];
   [tblViewContact registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
 }

 //Get Contact and Authorization Access

-(void)getContact
{
    // Request authorization to Contacts
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted == YES)
    {
      //keys with fetching properties
      NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
      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;
        NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
        NSMutableArray *arrContacts = [[NSMutableArray alloc]init];

        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:@"person-icon.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];
            [arrContacts addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
        }
        //Removing Duplicate Contacts from array
        NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:arrContacts];
        NSArray *arrayWithoutDuplicates = [orderedSet array];
        arrData = [arrayWithoutDuplicates mutableCopy];
        NSLog(@"The contacts are - %@",arrData);
        dispatch_async(dispatch_get_main_queue(), ^{
            [tblViewContact reloadData];
        });
       }
     }
  }];
}

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


 #pragma mark - UITableView Data Source Methods

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
  return 1;
 }

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

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static  NSString *strCell = @"cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
   if(cell==nil)
   {
      cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
   }
   cell.textLabel.text = arrData[indexPath.row];
   return cell;
 }

The Printed results For Contacts

The contacts are - (
 "John Appleseed",
 "Kate Bell",
 "Anna Haro",
 "Daniel Higgins",
 "David Taylor",
 "Hank Zakroff"
)

Screenshot below

When first you run the app

enter image description here

Now it shows contacts in table view

enter image description here

Upvotes: 5

Related Questions