如何在Swift中从QR码保存vCard [英] How to save vCard from QR code in Swift
本文介绍了如何在Swift中从QR码保存vCard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
swift中QR码的输出是一个字符串,如果Code包含带有swift
的vCard
,我需要保存QR Code
.
The output of the QR Code in swift is a String and i need to save QR Code
if the Code contains a vCard
with swift
.
我收到一条错误消息,提示它无法将CNContacts强制转换为CNMutableContacts
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
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
对象mutable
,这就是为什么会出现此错误的原因.像这样更改您的saveRequest.addContact
行
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.
这篇关于如何在Swift中从QR码保存vCard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文