2016-11-14 29 views
3

这是我的代码来获取设备的联系人并保存到MutableArray如何从CNContactStore获得RecordID ios

但我需要单独获取所有联系人的recordID并保存到相同的阵列中以备后用。 (例如,使用recordId删除联系人)。

请帮帮我,我被困了4天。

[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact* __nonnull contact, BOOL* __nonnull stop){ 
      if(contact.phoneNumbers) 
       phoneNumber = [[[contact.phoneNumbers firstObject] value]]; 
      if(contact.emailAddresses) 
       emailAddress = [[contact.emailAddresses firstObject] value]; 
      contactValue=[[NSMutableDictionary alloc] init];    
       [contactValue setValue:phoneNumber ?:@"" forKey:@"phoneNumber"]; 
       [contactValue setValue:emailAddress ?:@"" forKey:@"emailAddress"]; 
       [contactValue setObject:contact.identifier forKey:@"phoneIdentifier"]; 
       [contactValue setObject:contact.givenName ?:@"" forKey:@"firstName"]; 
       [contactValue setObject:contact.familyName ?:@"" forKey:@"lastName"]; 

      [_totalContact addObject:contactValue]; 
     }] 
+0

你在哪里卡住了?你无能为力? “保存到同一阵列中以备后用”是什么意思? – Adeel

+0

我想删除选定的联系人。你知道如何删除选定的联系人吗? – iOS

+0

看看下面的答案。我自己验证了这个代码,它的工作原理非常完美。 – Adeel

回答

3

从你的问题陈述我的理解是,你要delete一个基于该接触identifier接触从通讯录。当你有identifier那么这是所有你需要做的:

- (void)deleteContactWithIdentifier:(NSString *)identifier { 

    NSArray *keys = @[CNContactGivenNameKey, 
         CNContactPhoneNumbersKey, 
         CNContactEmailAddressesKey, 
         CNContactIdentifierKey]; 
    CNMutableContact *contact = [[store unifiedContactWithIdentifier:identifier keysToFetch:keys error:nil] mutableCopy]; 
    NSError *error; 
    CNSaveRequest *saveRequest = [[CNSaveRequest alloc] init]; 
    [saveRequest deleteContact:contact]; 
    [store executeSaveRequest:saveRequest error:&error]; 
} 
+0

感谢Adeel其完美的作品。 你可以如何合并重复的联系人? – iOS

+0

当然@InderpalSingh。我建议你问一个新的问题,因为它会在这篇文章中脱离主题。您可以在评论中添加新问题的链接。 – Adeel

+0

这里是链接@Adeel [链接](http://stackoverflow.com/questions/40613589/how-to-merger-the-duplicate-device-contacts-in-ios) – iOS

1

使用这种简单的扩展,如果你真的需要阅读recordID(旧API)。

recordID总是被提取。

此代码从不提交到App Store。它使用私人API!

CNContact+PrivateExtension.h

NS_ASSUME_NONNULL_BEGIN 

@interface CNContact (PrivateExtension) 

@property (readonly) NSNumber *privateRecordID; 

@end 

NS_ASSUME_NONNULL_END 

CNContact+PrivateExtension.m

@implementation CNContact (PrivateExtension) 

- (NSNumber *)privateRecordID 
{ 
    return [self valueForKey:@"recordID"]; 
} 

@end 
+0

你在iOS 11 beta上使用过?,在iOS 11的CNContact对象上使用valueForKey:@“recordID”崩溃并给出消息“此类不是关键记录ID的关键字值编码。”就好像Apple放弃了对ABAddressBook属性的支持一样 –