ios - 单击联系人按钮而不是设备的默认 View 时,在自定义 TableView Controller 中显示来自 iOS 设备的所有联系人

标签 ios objective-c uitableview contacts addressbook

在我的应用程序中,当我单击联系人按钮时,我需要在自定义表格 viewcontoller 中显示设备中的所有联系人。我发现很多使用地址簿框架的演示,但在其中联系人使用 ABPeoplePickerNavigationController 以默认设备格式显示。但我需要在自定义 View 中显示所有联系人。有什么办法可以做到这一点。我的应用程序也应该在 iOS7 及更高版本中运行。 Contacts Framework 可以在 iOS 7 和 8 中使用吗?我正在使用 xcode 7.2。请提供 Objective-C 中的解决方案,因为我不熟悉 swift。提前致谢。

最佳答案

在 iOS 9 中,AddressBook Framework 已弃用。请使用 Contact 框架。

我试过了,效果非常好。

非常完美的答案如下。

#import "ViewController.h"
#import <Contacts/Contacts.h>
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
   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 contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
}

关于ios - 单击联系人按钮而不是设备的默认 View 时,在自定义 TableView Controller 中显示来自 iOS 设备的所有联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595631/

相关文章:

iOS - 如何获取沿线指定距离的 CGPoint?

ios - Swift 委托(delegate)和协议(protocol)不起作用

iphone - 帮助在iPhone上实时更新声音

objective-c - 在 CATextLayer 中垂直居中文本

ios - 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?

ios - uicollectionview 的间距列

ios - 我的核心数据模型出了什么问题?

ios - 获取 REST 数据的模式 "lazily"

ios - 将 SubView 添加到 UITableViewCell 不会显示

ios - 在自定义表格单元格中更改 ImageView