1

出于某种原因,我的一些联系人从我的 tableView 中丢失了。我相信我是否获取了所有必要的密钥并查看了 Apple 的文档,但仍然卡住了。下面是我的代码:

  -(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"];
                }

                NSString *number = contact.phoneNumbers.firstObject.value.stringValue;

                if (number == (NSString *)NSNull.null || number == nil) {
                    [contactNumbersArray addObject:@"NO NUMBER"];
                } else {
                    [contactNumbersArray addObject:number];
                }


                arrayPhoneData = contactNumbersArray;
                NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
                [arrayTableData addObject:[NSString stringWithFormat:@"%@",[personDict objectForKey:@"fullName"]]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //[tableViewContactData reloadData];
                [self.tableView reloadData];
            });
        }
      }
  }];
}

任何帮助深表感谢!!!!

4

2 回答 2

0
`
let keys = [CNContactGivenNameKey, CNContactPhoneNumbersKey] as [Any]

        do {
            let contactStore = AppDelegate.getAppDelegate().contactStore
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])) { (contact, pointer) -> Void in
                if !contact.phoneNumbers.isEmpty {
                    contacts.append(contact)
                }
            }
        }
        catch let error as NSError {

            print(error.description, separator: "", terminator: "\n")
        }


        let contactPickerViewController = CNContactPickerViewController()

        contactPickerViewController.delegate = self

        present(contactPickerViewController, animated: true, completion: nil)
`

将其粘贴在您的应用程序委托中

var contactStore = CNContactStore()

   class func getAppDelegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }

尝试仔细检查您的谓词。我在限制我一直在搜索的联系人的谓词方面遇到了麻烦,并且在过去将其完全删除。并非如此,但您可以尝试向您的联系人密钥添加更多密钥。您可能会使用 keysToFetch 限制您的搜索。

于 2016-11-07T19:35:40.600 回答
0

您应该以不同的方式访问通讯录。

   dispatch_async(dispatch_get_main_queue(), ^{

    CNContactStore *store = [[CNContactStore alloc] init];

    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        if (granted == NO) {
            //show access denied popup
            return ;
        }


        NSError* contactError;
        CNContactStore* addressBook = [[CNContactStore alloc]init];
        [addressBook containersMatchingPredicate:[CNContainer predicateForContainersWithIdentifiers: @[addressBook.defaultContainerIdentifier]] error:&contactError];
        NSArray *keysToFetch = @[CNContactMiddleNameKey,CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey,CNContactEmailAddressesKey];
        CNContactFetchRequest * request = [[CNContactFetchRequest alloc]initWithKeysToFetch:keysToFetch];


        [addressBook enumerateContactsWithFetchRequest:request error:&contactError usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop){\

            NSString *firstName = contact.givenName;
            NSString *lastName = contact.familyName;

           //recommend to use a function like this one: [self parseContactWithContact:contact];
        }];


    }];
});
于 2017-05-10T11:55:16.577 回答