2016-01-09 3 views
0

Проверьте мой код:Как напечатать номер телефона через контакты в ячейке таблицы

#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 номер телефона не наступает.

Может быть, я где-то ошибся. Пожалуйста, помогите, заблаговременно.

+0

'NSLog (@"% @ ", телефон);' и 'NSLog (@"% @ ", fullName);' что-то печатают? –

+0

Да в консоли полное имя и номер телефона наступает –

+0

Я предполагаю, что серия результатов различного полного имени и номера подходит? –

ответ

1

Попробуйте это:

NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName", phone,@"phoneNumbers",profileImage,@"userImage" nil]; 

вместо:

NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage, nil]; 

Вы не обновляя словарь с требуемыми данными.

+1

. Прочитав эту кучу кода, я только что увидел это, когда вы разместили. «phoneNumbers» не может быть прочитан из его словаря в «cellForRow:», потому что он никогда не застрял в словаре. – NSGangster

+0

, но при отладке этой строки его показывает число, которое означает, что он загружает bt, не может отображать –

+0

«он загружается» - кто здесь «он»? –