在iphone中以编程方式将联系人添加到现有组

时间:2012-04-26 12:52:42

标签: ios addressbook abrecordref

我想将ABRecordRef添加到现有的Group。一些如何不工作。这是我的代码:

-(void)addUsers:(NSMutableArray*)users toGroupID:(ABRecordID)groupID {

    CFErrorRef error = NULL;
    ABAddressBookRef addressBookRef = ABAddressBookCreate();

   // Get Group 
    ABRecordRef group = ABAddressBookGetGroupWithRecordID(addressBookRef,groupID);

    for (User *user in users) {

        int recordId = user.uniqID;

        ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBookRef,(ABRecordID)recordId);

        //add the new person to the record
        ABAddressBookAddRecord(addressBookRef, person, nil); 
        ABAddressBookSave(addressBookRef, &error);

        // add the group   
        ABAddressBookAddRecord(addressBookRef, group, &error); 
        ABAddressBookSave(addressBookRef, &error);

        // add the person to the group 
        ABGroupAddMember(group, person, &error);         
        ABAddressBookSave(addressBookRef, &error);

        //save the record
        ABAddressBookSave(addressBookRef, nil);

        if (!isMemberAdded) {
            [self showAlertWithTitle:@"Alert" andMessage:@"Some Error Occured While Adding User to Existing Group"];
        }
    }
    BOOL isMembersAddedToGroup = ABAddressBookSave(addressBookRef, nil); 
    if (isMembersAddedToGroup) {
        [self showAlertWithTitle:@"Alert" andMessage:@"Selected Members Added to Existing Group Successfully"];
    }
    else{
        [self showAlertWithTitle:@"Alert" andMessage:@"Some Error Occured While Adding User to Existing Group"];
    }
    CFRelease(addressBookRef);
}

每当我使用上面的代码&尝试将其保存在现有组中我在控制台中收到以下消息

CPSqliteStatementPerform: constraint failed for INSERT INTO ABGroupMembers (group_id, member_type, member_id) VALUES (?, ?, ?);
CPSqliteStatementReset: columns group_id, member_type, member_id are not unique for INSERT INTO ABGroupMembers (group_id, member_type, member_id) VALUES (?, ?, ?);

我没有得到上面代码中缺少的内容。 任何帮助都是值得赞赏的。感谢

1 个答案:

答案 0 :(得分:3)

如果我们看到消息:

CPSqliteStatementPerform: constraint failed for INSERT INTO ABGroupMembers (group_id, member_type, member_id) VALUES (?, ?, ?);
CPSqliteStatementReset: columns group_id, member_type, member_id are not unique for INSERT INTO ABGroupMembers (group_id, member_type, member_id) VALUES (?, ?, ?);

同样在documentation

  

ABAddressBook opaque类型(其实例称为地址   books)为Address Book-a提供了一个编程接口   多个应用程序用于存储个人的集中式数据库   关于人的信息

(因此,在内部,此错误是由于不正确的sqlite查询引起的。)

表示ABGroupAddMemberABAddressBookAddRecord(addressBookRef, group, &error);来电存在问题。

问题可能是:当我们调用ABAddressBookGetGroupWithRecordIDABAddressBookGetGroupWithRecordID函数时,我们已经向我们提供了群组和个人参考。

现在,当ABAddressBookAddRecordperson同时执行group时,它会将其添加到addressbook,但不会更新其UniqueIds id for person and group ref.)因此,在ABGroupAddMember函数调用时,persongroup具有ABGroupMembers表中添加的相同ID。

请在将recordIdperson添加到地址簿之后(以及将它们添加到群组之前)尝试打印group。如果recordsIds未更新,那么这就是原因,您需要为新record提取recordId。同时检查是否将新的persongroup添加到地址簿中。

*目前,我没有mac访问来验证我的建议/答案。