向二维码添加多个键值对

Adding Multiple Key-Value Pairs to QR Code(向二维码添加多个键值对)

本文介绍了向二维码添加多个键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的应用程序中创建二维码,我想知道是否可以添加第二个键-值对。现在我有一个12位数字的"inputMessage"键,我想要另一个键的一些其他数据。例如,使用另一个字符串作为名为"GORM"的新密钥。

以下是我创建二维码的函数:

func generateCode() {
        let gymData = gymName.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
        let codeNumberData = generateRandomNumber(12).dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)

        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(codeNumberData, forKey: "inputMessage")
        // filter?.setValue(gymData, forKey: "gym")
        filter?.setValue("Q", forKey: "inputCorrectionLevel")

        let qrCodeImage = filter?.outputImage
        let context = CIContext(options: nil)
        let cgImage = context.createCGImage(qrCodeImage!, fromRect: (qrCodeImage?.extent)!)

        let image = UIImage(CGImage: cgImage, scale: 1.0, orientation: .Up)
        let resized = resizeImage(image, withQuality: CGInterpolationQuality.None, rate: 5.0)
        codeImageView.image = resized
    }

推荐答案

CIFilter仅期望从inputMessage生成二维码,因此您需要创建单个聚合inputMessage并将其传递给过滤器。要做到这一点,一种相当简单的方法是根据您的输入创建一个字典,使用NSKeyedArchiver将其序列化为NSData BLOB,然后将结果设置为inputMessage

func generateCode() {
    var aggregateData = [String: NSData]()

    if let gymData = gymName.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false) {
        aggregateData.updateValue(gymData, forKey: "gymData")
    }

    if let codeNumberData = generateRandomNumber(12).dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false) {
        aggregateData.updateValue(codeNumberData, forKey: "codeNumberData")
    }

    let archived = NSKeyedArchiver.archivedDataWithRootObject(aggregateData)
    let filter = CIFilter(name: "CIQRCodeGenerator")

    filter?.setValue(archived, forKey: "inputMessage")
    filter?.setValue("Q", forKey: "inputCorrectionLevel")

    let qrCodeImage = filter?.outputImage
    let context = CIContext(options: nil)
    let cgImage = context.createCGImage(qrCodeImage!, fromRect: (qrCodeImage?.extent)!)

    let image = UIImage(CGImage: cgImage, scale: 1.0, orientation: .Up)
    let resized = resizeImage(image, withQuality: CGInterpolationQuality.None, rate: 5.0)
    codeImageView.image = resized
}

当然,这意味着在接收端,您需要期望有效负载是一个字典,并通过它们的键访问各个组件。应该是这样的。

guard let inputData = scannedQrString.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false),
    dictionary = NSKeyedUnarchiver.unarchiveObjectWithData(inputData) as? [String: NSData] else {
    return
}

let gymData = dictionary["gymData"]
let codeNumberData = dictionary["codeNumberData"]

这篇关于向二维码添加多个键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:向二维码添加多个键值对

基础教程推荐