如何生成带有详细信息数量的QRCode

时间:2019-01-10 12:08:57

标签: ios swift qr-code

我没有使用QRCode生成器和扫描仪的经验,但是我尝试从下面显示的字符串生成QRCode。我想使用诸如地点地址,姓名,手机号码,邮件,网站,任何文档之类的值来生成它。谁能帮助我做到这一点。

@IBAction func generate(_ sender: Any) {
    if let mystring = mytextfield.text       {

        let data = mystring.data(using: .ascii, allowLossyConversion: false)
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(data, forKey: "InputMessage")
        let ciImage = filter?.outputImage
        let  transform = CGAffineTransform(scaleX: 10, y: 10)
        let transformimage = ciImage?.transformed(by: transform)
        let image = UIImage(ciImage: transformimage!)
        img.image=image
        saveimg.isEnabled=true
    }


}

@IBAction func saveimage(_ sender: Any) {
    screenshotmethod()
}
func screenshotmethod(){
    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil)
}

3 个答案:

答案 0 :(得分:1)

尝试将详细信息从Dictionary转换为JSON数据,然后将其设置为CIFilter

var jsonDict = [String: Any]()
jsonDict.updateValue("Your_Name", forKey: "name")
jsonDict.updateValue("1234567890", forKey: "number")
guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict, options: [.prettyPrinted]) else {
    return
}
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(jsonData, forKey: "InputMessage")

答案 1 :(得分:0)

通过将任何字符串发送到以下函数,您可以轻松生成 QRCode

private func generateQRCode(from data: Data) -> UIImage? {

    if let filter = CIFilter(name: "CIQRCodeGenerator") {
        filter.setValue(data, forKey: "inputMessage")
        let transform = CGAffineTransform(scaleX: 10, y: 10)
        if let output = filter.outputImage?.transformed(by: transform) {
            return UIImage(ciImage: output)
        }
    }
    return nil

}

答案 2 :(得分:0)

我用这种方式

private func generateQRCode(){
    var jsonDict = [String: Any]()
    jsonDict.updateValue("Your_Name", forKey: "name")
    jsonDict.updateValue("1234567890", forKey: "number")
    guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict, options: [.prettyPrinted]) else {
        return
    }
    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter?.setValue(jsonData, forKey: "InputMessage")
    let qrTransform = CGAffineTransform(scaleX: 12, y: 12)
    let qrImage = filter?.outputImage?.transformed(by: qrTransform)
    img_ticket_qr.image = UIImage(ciImage: qrImage!)
}