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

标签 ios swift

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

我收到一个错误,提示它无法将 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 对象转换为 mutable,这就是您收到此错误的原因。像这样更改 saveRequest.addContact

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

希望对您有所帮助。

关于ios - 如何在 Swift 中从二维码保存 vCard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38051598/

相关文章:

ios - 应用程序的通话状态栏

ios - 在swift 2中从对象和键数组创建字典

ios - 从 Swift 5 iOS 应用程序进行 Mailchimp API 调用时“API key 丢失”

ios - 为什么我的 iPhone 应用程序在收到内存警告时会崩溃?

ios - 为什么我的 Tabbar 的用户交互在从 popviewcontroller 到另一个 View 时启用?

ios - 从 coredata swift 获取特定属性

ios - 升级到 swift 2.1 后,Swift 返回可选的 ("value")

ios - 快速框架中的编译器标志

ios - 在两个类之间使用 NSDictionary 值

objective-c - 如何在 iOS 中监控后台位置?