Search code examples
swiftcontacts-framework

Unable to update a contact's phone number in Swift


Went through many blogs, questions and articles before posting this question. I'm not able to update phone number for a contact using Contacts framework in Swift.

let store = CNContactStore()
OperationQueue().addOperation{[store] in
let predicate = CNContact.predicateForContacts(matchingName: "XYZ")
let toFetch = [CNContactPhoneNumbersKey, CNContactGivenNameKey]

        do{
            let contacts = try store.unifiedContacts(matching: predicate,
                                                     keysToFetch: toFetch as [CNKeyDescriptor])

            for Contact in contacts{
                let XYZ = Contact.mutableCopy() as! CNMutableContact
                print("Name: ", XYZ.givenName)
                print(XYZ.phoneNumbers.count)
                for CNPhoneNumber in XYZ.phoneNumbers{
                    print("Phone number: ", CNPhoneNumber.value)
                    var text = CNPhoneNumber.value.stringValue
                    let matchText = text.starts(with: "011 91")
                    if(matchText == true){
                        let start = text.index(text.startIndex, offsetBy: 0);
                        let end = text.index(text.startIndex, offsetBy: 8);
                        text.replaceSubrange(start..<end, with: "+91")
                        print("Replaced number: ",text)
                    } else{
                        print("Phone number is not starting with 011 91")
                    }
                    let phoneNumber = CNLabeledValue(label: CNLabelPhoneNumberiPhone, value:CNPhoneNumber(stringValue: text))
                    XYZ.phoneNumbers[0] = phoneNumber

                    let req = CNSaveRequest()
                    req.update(XYZ)
                    try store.execute(req)
                }
            }
        }
         catch let err{
            print(err)
        }
    }

enter image description here


Solution

  • Found the culprit

    change CNPhoneNumber to any other valid literal

    for CNPhoneNumber in daddy.phoneNumbers
    

    to

    for phoneNumber in daddy.phoneNumbers
    //change the rest of the for-in loop accordingly
    

    The reason is, upper code portion declare CNPhoneNumber as a CNLabeledValue<CNPhoneNumber> object, and the error saying to you that you tried to call a value for non-function type object CNLabeledValue<CNPhoneNumber>