如何在Swift中从QR码中保存vCard

时间:2016-06-27 10:28:02

标签: ios swift

swift中QR码的输出是一个字符串,如果代码包含QR Code vCard,我需要保存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

            }
        }
    }
 }

1 个答案:

答案 0 :(得分:1)

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

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

希望这会对你有所帮助。