alovii alovii - 4 months ago 48
Swift Question

How to save vCard from QR code in Swift

The output of the QR Code in swift is a String and i need to save

QR Code
if the Code contains a

I am getting an error that says it cannot cast CNContacts to 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


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



You are trying to convert immutable object mutable, that's why you are getting this error. Change you saveRequest.addContact line like this

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

Hope this will help you.