向QR码添加多个键值对

时间:2016-03-09 16:00:40

标签: ios swift qr-code

我正在我的应用中创建QR码,我想知道是否可以添加第二个键值对。现在我有一个12位数字的“inputMessage”键,我想要另一个键的其他数据。例如,使用另一个字符串作为名为“gym”的新键。

以下是我创建QR码的功能:

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
    }

1 个答案:

答案 0 :(得分:2)

CIFilter只希望从inputMessage生成QR码,因此您需要创建一个聚合inputMessage并将其传递给过滤器。一种相当直接的方法是从输入创建一个Dictionary,使用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"]