Dinesh Kaushik
Dinesh Kaushik

Reputation: 2987

iPhone: Adding contact to a group not working on device but working on simulator in ABAddressbook

Adding contact to a group not working on device but working on simulator in ABAddressbook Gives no error but contact is not reflected in particular group in contacts but works fine on Simulator

I am Using this code

if (person) {
           ABAddressBookAddRecord(addressBook, person, nil);

           ABAddressBookSave(addressBook, &error);

           BOOL isADDED = ABGroupAddMember(groupNameRef, person, &error);

           NSError *error1 = (__bridge_transfer NSError *)error;

           NSLog(@"Reason = %@", error1.localizedFailureReason);
           BOOL iSSaved = ABAddressBookSave(addressBook, &error);
}

works fine on Simulator but not on device

Upvotes: 2

Views: 426

Answers (1)

matt
matt

Reputation: 535027

It will help you to start by using error-checking correctly. Here is the structure of an error-checked routine:

if (person) {
    bool ok;
    CFErrorRef err = nil;
    ok = ABAddressBookAddRecord(addressBook, person, &err);
    if (!ok) {
        NSLog(@"%@", err);
        return;
    }
    ok = ABAddressBookSave(addressBook, &err);
    if (!ok) {
        NSLog(@"%@", err);
        return;
    }
    ok = ABGroupAddMember(groupNameRef, person, &err);
    if (!ok) {
        NSLog(@"%@", err);
        return;
    }
    ok = ABAddressBookSave(addressBook, &err);
    if (!ok) {
        NSLog(@"%@", err);
        return;
    }
}

Notice the pattern here. The function returns a bool. You examine that bool. If it is false, then you examine the error returned by indirection. If you follow this pattern correctly, you will get better information about what is going wrong.

Edit: Make sure you actually have access to the contacts database. I'm assuming you do, but a major difference between the Simulator and the device is that the Simulator grants access automatically, whereas on the device the user must be presented with the access request dialog (call ABAddressBookRequestAccessWithCompletion) or else there won't be access and attempts to work with the contacts database will fail, perhaps silently.

Upvotes: 2

Related Questions