5

在发布这个问题之前,浏览了许多博客、问题和文章。我无法使用 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)
        }
    }

在此处输入图像描述

4

1 回答 1

2

找到了罪魁祸首

更改CNPhoneNumber 为任何其他有效文字

for CNPhoneNumber in daddy.phoneNumbers

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

原因是,上面的代码部分声明CNPhoneNumber为一个CNLabeledValue<CNPhoneNumber>对象,并且错误告诉你你试图为非函数类型对象调用一个值CNLabeledValue<CNPhoneNumber>

于 2018-04-09T18:09:10.407 回答