私はデバイス上のすべての連絡先の名前を表示するテーブルビューを持っています。これらの名前は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 [email protected][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
答えが答えを –
@simon_smileyありがとうと受け入れるためにあなたの質問を解決したかどうか忘れないでください、Simon。私は今週決勝を終えているので、まだ試してはいけません。私の質問に対する大きな答えのようです。 –