如何在 Swift 中从二维码保存 vCard

2023-12-26

swift 中二维码的输出是一个字符串,我需要保存QR Code如果代码包含vCard with swift.

我收到一条错误消息,指出它无法将 CNContacts 转换为 CNMutableContacts

func foundCode(code: NSString) {

    // Check if the QR Code is a website, contact, text etc

    let types :NSTextCheckingType = [.Link , .PhoneNumber, .TransitInformation]


    let checkTextType =  try? NSDataDetector(types: types.rawValue )

    let matchs = checkTextType?.matchesInString(code as String, options: .ReportCompletion, range: NSMakeRange(0, (code as String).characters.count))

    for match in matchs! {
        if match.resultType == NSTextCheckingType.Link {
            UIApplication.sharedApplication().openURL(NSURL(string: code as String)!)
        }
        if match.resultType == NSTextCheckingType.PhoneNumber {

            let vcard: NSData = code.dataUsingEncoding(NSUTF8StringEncoding)!
            let contactStore = CNContactStore()


            do {

                let saveRequest = CNSaveRequest() // create saveRequests

                let contacts  = try? CNContactVCardSerialization.contactsWithData(vcard) // get contacts array from vCard

                print("\(contacts)")

                for person in contacts! {


                      saveRequest.addContact(person as! CNMutableContact, toContainerWithIdentifier: nil) // add contacts to saveRequest

                }

                try contactStore.executeSaveRequest(saveRequest) // save to contacts

            } catch  {

                print("Unable to show the new contact") // something went wrong

            }
        }
    }
 }

您正在尝试转换immutable object mutable,这就是您收到此错误的原因。改变你saveRequest.addContact像这样的线

saveRequest.addContact(person.mutableCopy() as! CNMutableContact, toContainerWithIdentifier: nil)

希望对你有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Swift 中从二维码保存 vCard 的相关文章

随机推荐