Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ABAddressBook - How to find if a particular contact is modified or deleted from iPhone's address book?

I am working on a chat app. For which i need to save contacts. So i am saving all contacts from ABAddressBook in my core data entity. Problem is how can i know if a contact is modified or removed from iPhone's AddressBook? So that i will modify or remove that contact from my Core data entity.

if ABRecordGetRecordID(person) can be used as unique key or not

Given belew is code of adding contacts in core data.

ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBookRef );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBookRef );

for ( int i = 0; i < nPeople; i++ )
{
    ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
 } 

 NSString* firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);


    if ([firstName hasPrefix:@"Protected by True"])
    {
        continue;
    }
    else if([firstName hasPrefix:@"Identified As Spam"])
    {
        continue;
    }


    NSString* lastName  = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);

    NSString *userEmail = nil;
    ABMultiValueRef emailData = ABRecordCopyValue(person, kABPersonEmailProperty);
    if(ABMultiValueGetCount(emailData) > 0) {
        NSLog(@"email is:%@",(__bridge NSString *)ABMultiValueCopyValueAtIndex(emailData, 0));
        userEmail = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emailData, 0);
    }

    NSString* phone = nil;
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phoneNumbers) > 0)
    {
        for (int i=0; i<ABMultiValueGetCount(phoneNumbers); i++)
        {
            phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, i);



            NSString *asciiCharacters = @"0123456789";
            NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet];





            NSString *stringPhone = [[phone componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString: @""];
            NSString *str = stringPhone;
            stringPhone = [str stringByReplacingOccurrencesOfString:@"^0+"
                                                         withString:@""
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, str.length)];






            NSLog(@"modified %@", stringPhone);

            NSString *phoneLabelLocalized;
            CFStringRef labelStingRef = ABMultiValueCopyLabelAtIndex (phoneNumbers, i);
            phoneLabelLocalized = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(labelStingRef);


            if ([[PersistentStore getMyJID] rangeOfString:stringPhone].location != NSNotFound)
            {
                NSLog(@"my phone  %@",stringPhone);
                continue;
            }

            NSFetchRequest *request = [[NSFetchRequest alloc] init];
                request.entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:appDelegate.managedObjectContext];
                request.predicate = [NSPredicate predicateWithFormat:@"contactNumber = %@", stringPhone];
                NSError *executeFetchError = nil;
                Contact  *contact = [[appDelegate.managedObjectContext executeFetchRequest:request error:&executeFetchError] lastObject];

                if (!contact)
                {
                    contact = (Contact *)[NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:appDelegate.managedObjectContext];
                    [contact setContactFirstName:firstName];
                    [contact setContactLastName:lastName];

                    if (firstName && lastName)
                    {
                        [contact setContactFullName:[NSString stringWithFormat:@"%@ %@",firstName,lastName]];
                    }
                    else if(firstName)
                    {
                       [contact setContactFullName:firstName];
                    }
                    else
                    {
                        [contact setContactFullName:lastName];

                    }
                    [contact setContactType:phoneLabelLocalized];
                    [contact setContactDate:[NSDate date]];
                    [contact setContactOriginalNumber:phone];
                    [contact setContactNumber:stringPhone];
                    [contact setContactEmail:userEmail];
                    [arrayContacts addObject:stringPhone];

                }

            }
        }
        CFRelease(phoneNumbers);


        NSError *error;
        if (![appDelegate.managedObjectContext save:&error])
        {
            // This is a serious error saying the record could not be saved.
            // Advise the user to restart the application
        }
    }
like image 228
Gagan Joshi Avatar asked May 05 '15 06:05

Gagan Joshi


1 Answers

ABAddressBookRegisterExternalChangeCallback will give you a callback whenever the address book changes.

ABRecordGetRecordID gives you the unique identifier for the address book entry (scoped to the device, not globally unique).

Those two things are enough for you to detect records being modified and deleted.

like image 53
Ewan Mellor Avatar answered Nov 24 '22 20:11

Ewan Mellor