Display all contacts from the iOS device in custom table viewcontoller when contacts button is clicked rather than default view of the device

后端 未结 2 641
春和景丽
春和景丽 2021-01-19 19:32

In my app I need to display all contacts from the device in a custom table viewcontoller when I click contacts button. I found a lot of demos using addressbook framework but

2条回答
  •  抹茶落季
    2021-01-19 20:05

    In iOS 9 AddressBook Framework is deprecated.Kindly use Contact framework.

    I tried, and it works fabulously.

    Very Perfect answer is below.

    #import "ViewController.h"
    #import 
    @interface ViewController ()
    {
       UITableView *tableViewContactData;
       NSMutableArray *arrayTableData;
    }
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad 
    {
      [super viewDidLoad];
      // Do any additional setup after loading the view, typically from a nib.
    
      arrayTableData = [[NSMutableArray alloc]init];
      [self fetchContactsandAuthorization];
      tableViewContactData = [[UITableView alloc] init];
      tableViewContactData.frame = CGRectMake(0, 50, 320, 518);
      tableViewContactData.delegate = self;
      tableViewContactData.dataSource = self;
      [tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
      [self.view addSubview:tableViewContactData];
    }
    
    - (void)didReceiveMemoryWarning {
      [super didReceiveMemoryWarning];
       // Dispose of any resources that can be recreated.
    }
    
    //UITAbleView Deleate methods
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
      return 1;
    }
    
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
       return  arrayTableData.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 = arrayTableData[indexPath.row];
      return cell;
    }
    
    //This is for fetching contacts from iPhone.Also It asks authorization permission.
    -(void)fetchContactsandAuthorization
    {
       // 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];
                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];
                    [arrayTableData addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
                    NSLog(@"The contactsArray are - %@",arrayTableData);
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [tableViewContactData reloadData];
                });
            }
        }
    }];
    }
    @end
    

    The output is

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

提交回复
热议问题