Programmatically create a group in contacts

╄→尐↘猪︶ㄣ 提交于 2019-12-21 06:45:06

问题


How to programmatically add a new group to the iPhone contact using AddressBook framework?


回答1:


First look and see if it exists, and if not, create it:

bool foundIt = NO;
// Protective - did we just not find it, or lose it?
CFArrayRef groups = ABAddressBookCopyArrayOfAllGroups(addrBook);
CFIndex numGroups = CFArrayGetCount(groups);
for(CFIndex idx=0; idx<numGroups; ++idx) {
    ABRecordRef groupItem = CFArrayGetValueAtIndex(groups, idx);

    CFStringRef name = (CFStringRef)ABRecordCopyValue(groupItem, kABGroupNameProperty);
//NSLog(@"Look at group named %@", name);
    bool isMatch = [newName isEqualToString:(NSString *)name];
    CFRelease(name);

    if(isMatch) {
        // NSLog(@"FOUND THE GROUP ALREADY!");
        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
        [self setObject:groupNum forKey:kGroupID];
        foundIt = YES;
        break;
    }
}
CFRelease(groups);

if(!foundIt) {
    // lets create one
    ABRecordRef groupItem = ABGroupCreate();
    ABRecordSetValue(groupItem, kABGroupNameProperty, (CFStringRef *)newName, &error);
    if(!error) {
        ABAddressBookAddRecord (addrBook, groupItem, &error);   // bool ret = 
        ABAddressBookSave(addrBook, &error);

        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
            //NSLog(@"FIRST groupNumber: %@", groupNum);
        [self setObject:groupNum forKey:kGroupID];
    }
    CFRelease(groupItem);
}


来源:https://stackoverflow.com/questions/11612781/programmatically-create-a-group-in-contacts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!