我有一个表格视图,显示设备上所有联系人的姓名。这些名称来自一个名为contactsArray
. 对于每个contact
对象,我获取phoneNumbers
对象并将数字拉入另一个名为phoneNumberArray
. 当我将它们放入我的表格视图时,它会显示每个联系人及其对应的号码......但只有这么长时间。当我下来几十行时,数字不再与正确的联系人匹配,因为某些contact
对象包含一个phoneNumbers
具有多个电话号码的对象。如何仅获取每个对象的第一个电话号码,以便我拥有相同数量的联系人和电话号码?
这是我的代码:
@property (nonatomic, strong) NSMutableArray *contactsArray;
@property (nonatomic, strong) NSMutableArray *phoneNumberArray;
@end
@implementation Contacts
- (void)viewDidLoad
{
[super viewDidLoad];
self.phoneNumberArray = [[NSMutableArray alloc]init];
self.contactsArray = [[NSMutableArray alloc]init];
[self fetchContactsandAuthorization];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.contactsArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"contactCell";
ContactCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
CNContact *contact = self.contactsArray[indexPath.row];
NSString *phone = self.phoneNumberArray[indexPath.row];
NSString *contactName = [NSString stringWithFormat:@"%@ %@",contact.givenName,contact.familyName];
NSString *contactNumber = phone;
cell.name.text = contactName;
cell.number.text = contactNumber;
[cell.inviteBtn addTarget:self action:@selector(openMessagesForContact:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 72;
}
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES)
{
CNContactStore *addressBook = [[CNContactStore alloc]init];
NSArray *keysToFetch =@[CNContactFamilyNameKey,
CNContactGivenNameKey,
CNContactPhoneNumbersKey];
CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc]initWithKeysToFetch:keysToFetch];
[addressBook enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
[self.contactsArray addObject:contact];
NSString *phone;
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
[self.phoneNumberArray addObject:phone];
}
}
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.contactsTableView reloadData];
});
}
}];
}
@end