简体   繁体   中英

how to update CNContact? Get CNErrorDomain Code=2

I'm trying to update your contacts in the caste controller, all well preserved up to a point, this is when adding new numbers that have CNLabeledValue <CNPhoneNumber> format. I brought in the console result I get this error

CNErrorDomain Code = 2 "(null)" UserInfo = {CNKeyPaths = (
     phoneNumbers
)},

As I looked at how to create the essence of the hotel and they do not have an example of an indicator

<CNLabeledValue: 0x1706755c0: identifier = (null), label = iPhone, value = <CNPhoneNumber: 0x170439100: countryCode = ru, digits = + ***** >>

My code

  for i in 0..<contactPhoneEditTableViewRowIndex {
        debugPrint("i", i)
        if let editRow = getEditPhoneRow(i) {
            if !editRow.isHidden {
                let phone = editRow.cell.phoneNumberTextField.text ?? ""
                let label = editRow.cell.titlePhoneButton.titleLabel?.text ?? ""
                if phone != "" {
                    let phoneModel = CNLabeledValue<CNPhoneNumber>().settingLabel(label, value: CNPhoneNumber(stringValue: phone))

                    phones.append(phoneModel)
                }
            }
        }
    }

    debugPrint(phones)

    guard let updatedContactModel = contactModel.contact.mutableCopy() as? CNMutableContact else { return }

    updatedContactModel.givenName = first
    updatedContactModel.familyName = last
    updatedContactModel.organizationName = company
    updatedContactModel.phoneNumbers = phones

    contactManager.updateContact(updatedContactModel) { [weak self] (error) in
        if error == nil {
            self?.dismiss(animated: true, completion: nil)
        } else {
            DispatchQueue.main.async {
                SVProgressHUD.showError(withStatus: error!.localizedDescription)
            }
        }
    }

This function from ContactManager

func updateContact(_ contact: CNMutableContact, completion: ((_ error: Error?) -> Void)?) {
    let req = CNSaveRequest()
    req.update(contact)
    let store = CNContactStore()
    do {
        try store.execute(req)
        debugPrint("updateContact success")
        completion?(nil)
    } catch {
        completion?(error)
        let _error = error as NSError
        debugPrint(_error)
    }
}

Tell me how I can fix this?

I changed this code

let phoneModel = CNLabeledValue<CNPhoneNumber>().settingLabel(label, value: CNPhoneNumber(stringValue: phone))

to let phoneModel = CNLabeledValue(label: phoneLabel, value: CNPhoneNumber(stringValue: phone)) and it solved my problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM