How to Get updated/added/deleted contact using CNContactStoreDidChangeNotification

1.7k views Asked by At

i made app using contact book contacts.

Problem:- i update/add/delete contact from contact book then back to my app.

My app applicationDidBecomeActive active write following code :-

NotificationCenter.default.addObserver(
        self,
        selector: #selector(self.addressBookDidChange),
        name: NSNotification.Name.CNContactStoreDidChange,
        object: nil)

After that addressBookDidChange method called multiple times and App UI freeze. i also tried to load contact in background but app crash randomly.

1) Contact Array declaration :-

 public var GlobalContactArray = [ContactEntry]()

2)load contact in background :-

    DispatchQueue.main.async
    {

            PKHUD.sharedHUD.contentView = PKHUDProgressView()
            PKHUD.sharedHUD.show()

    }

   DispatchQueue.global(qos: .background).async
   {
        self.requestAccessToContacts
        { (success) in
            if success
            {
                self.retrieveContacts({ (success, contacts ) in

                    if success && (contacts?.count)! > 0
                    {
                        self.GlobalContactArray = contacts!

                        for arrcontact in contacts!
                        {
                            self.GetStoreConatcts(arrcontact)
                        }

                     }
                })
            }
        }
    }

3) retrieveContacts method :-

self.GlobalContactArray.removeAll()


        do
        {
            let contactsFetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactImageDataAvailableKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor])
            try contactStore.enumerateContacts(with: contactsFetchRequest, usingBlock:
            {
                (cnContact, error) in
                if let contact = ContactEntry(cnContact: cnContact)
                {
                    if self.GlobalContactArray.contains(contact)
                    {

                    }
                    else
                    {
                        self.GlobalContactArray.append(contact)
                    }


                }
            })

                if self.GlobalContactArray.count == 0
                {

                }
                else
                {
                    if Constants.isLogin == "1"
                    {
                        DispatchQueue.main.async
                        {
                            NotificationCenter.default.post(name: Notification.Name("LoadContactList"), object: nil)
                        }

                    }
                    else
                    {
                        UserDefaults.standard.set(true, forKey: "ContactViewDisapper")
                        UserDefaults.standard.synchronize()
                    }

                }

            completion(true, self.GlobalContactArray)
        }
        catch
        {
            completion(false, nil )
        }

4) After completion of this method update/add contact in local Db using core Database.For add/update local Db method name is "self.GetStoreConatcts(arrcontact)".In this pass one by one contact.Using this contact check in db if available then update contact and not available then add contact.

i followed above all steps contact also update/add/delete but app crash randomly.

so anyone have solution for how to load method in background then please help me.

Thanks in advance.

1

There are 1 answers

3
Satish Babariya On BEST ANSWER

Try using SwiftyContacts Cocoapods Library.

https://cocoapods.org/pods/SwiftyContacts

Fetch Contacts on Background Thread

fetchContactsOnBackgroundThread(completionHandler: { (result) in
    switch result{
        case .Success(response: let contacts):
            // Do your thing here with [CNContacts] array    
            break
        case .Error(error: let error):
            print(error)
            break
    }
})

Add Contact

let contact : CNMutableContact = CNMutableContact()
contact.givenName = "Satish"
// OR Use contact.mutableCopy() For Any CNContact

addContact(Contact: contact) { (result) in
    switch result{
        case .Success(response: let bool):
            if bool{
                print("Contact Sucessfully Added")
            }
            break
        case .Error(error: let error):
            print(error.localizedDescription)
            break
    }
}

Delete Contact

// Use contact.mutableCopy() To convert CNContact to CNMutableContact
deleteContact(Contact: contact) { (result) in
    switch result{
        case .Success(response: let bool):
            if bool{
                print("Contact Sucessfully Deleted")
            }
            break
        case .Error(error: let error):
            print(error.localizedDescription)
            break
    }
}