联系人框架在添加电话号码时导致应用程序崩溃。

4

在尝试更新现有联系人时,我遇到了sigabrt错误“在获取联系人时未请求属性”。

var cntct= existingContact.mutableCopy() as! CNMutableContact

let phone= CNLabledValue(label:CNLabelPhoneNumberMain, value:"786967655566") 

cntct.phoneNumbers.append(phone)

错误提示说,您正在访问在获取时未使用keysToFetch请求的属性。更多信息请参见:https://developer.apple.com/documentation/contacts/cncontact/1403210-iskeyavailable - Saran
1个回答

0

我在自己的相关问题上苦苦挣扎了几个小时:我需要使用Swift向联系人添加生日。通过一些研究、试验和故障排除,我得出了以下结论:

    var contactStore = CNContactStore()
    var contactx:CNMutableContact = CNMutableContact()

    let predicate = CNContact.predicateForContactsMatchingName("\(firstnamefield.text!) \(lastnamefield.text!) \(suffixfield.text!)") // searches for contacts matching the inserted name (inputted by the user as first name, then last name, then any suffixes).

    let toFetch = [CNContactBirthdayKey]
    do{
        var contacts = try contactStore.unifiedContactsMatchingPredicate(
            predicate, keysToFetch: toFetch)

        print(contacts)

        for contact in contacts {

            let birthday = NSDateComponents()
            birthday.year = Int(yearfield.text!)! // sets the birthday year
            birthday.month = Int(monthfield.text!)! // sets the birthday month
            birthday.day = Int(dayfield.text!)! // sets the birthday day

            let mutableContact = contact.mutableCopy() as! CNMutableContact
            mutableContact.birthday = birthday // sets the contacts found with predicate search to having the birthday set above.

            let saveRequest = CNSaveRequest()
            saveRequest.updateContact(mutableContact)
            try contactStore.executeSaveRequest(saveRequest)

显然,这里添加的是生日而不是电话号码,但您可以使用完全相同的原则(谓词搜索,对于联系人中的联系人)来添加电话号码;只需更改循环内发生的事情即可!希望这能帮助到您,很抱歉您之前没有得到回复。

基本上,您可以更改联系人循环内部的内容为

let phone= CNLabledValue(label:CNLabelPhoneNumberMain, value:"786967655566") 

cntct.phoneNumbers.append(phone)

而且你应该有一个添加电话号码的过程。


@Aslam,我希望这能对你有所帮助;如果需要将其转换为添加电话号码,请告诉我,我可以帮忙! - owlswipe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接