Проверьте мой код:Как напечатать номер телефона через контакты в ячейке таблицы
#import "ContactViewController.h"
#import "SimpleTableCell.h"
@import Contacts;
@import ContactsUI;
@interface ContactViewController()
@end
@implementation ContactViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_Contacts = [[NSMutableArray alloc]init];
_fullName = [[NSMutableArray alloc]init];
_phone = [[NSMutableArray alloc]init];
[self fetchContacts];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) fetchContacts
{
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;
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:@"acc_sett.png "];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
NSMutableArray *cleanArray = [[NSMutableArray alloc] initWithCapacity:0];
// Here 'Activity' is your NSArray. A better name would be 'activity'
// (save capitalized names for classes)
for (NSString *item in contactNumbersArray)
{
[cleanArray addObject:[[item componentsSeparatedByString:@"-"] lastObject]];
}
NSLog(@"%@",cleanArray);
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage, nil];
[_Contacts addObject:personDict];
NSLog(@"%@",phone);
NSLog(@"%@",fullName);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.contacttableview reloadData];
});
}
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_Contacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* personDict = [_Contacts objectAtIndex:indexPath.row];
static NSString *simpleTableIdentifier = @"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.Name.text = [personDict objectForKey:@"fullName"];
cell.Phone.text = [personDict objectForKey:@"phoneNumbers"];
cell.thumbnailImageView.image = [personDict objectForKey:@"userImage"];
NSData *dataItems=UIImageJPEGRepresentation(cell.thumbnailImageView.image, 0.1);
NSString *[email protected]"userImage";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDirectry=[path objectAtIndex:0];
NSString *fullpathfile=[DocumentDirectry stringByAppendingPathComponent:mysavedimage];
[dataItems writeToFile:fullpathfile atomically:YES];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:@"showDetail" sender:self];
}
@end
С помощью этого кода fullname
и image
из контактов человека приходит на просмотр таблицы, но номер телефона не подходит и я использую пользовательскую ячейку для отображения и одну вещь после получения контактов с симулятора в номере телефона консоли, и полное имя идет на консоль, но на Table View номер телефона не наступает.
Может быть, я где-то ошибся. Пожалуйста, помогите, заблаговременно.
'NSLog (@"% @ ", телефон);' и 'NSLog (@"% @ ", fullName);' что-то печатают? –
Да в консоли полное имя и номер телефона наступает –
Я предполагаю, что серия результатов различного полного имени и номера подходит? –