Swift
Swift

Reputation: 1184

How to generate QRCode image with parameters in swift?

I need to create QRCode image with app registered users 4 parameters, so that if i scan that QRCode image from other device i need to display that user details, that is my requirement.

here i am getting registered user details: with these parameters i need to generate QRCode image

    var userId = userModel?.userId
    var userType = userModel?.userType
    var addressId = userModel?.userAddrId
    var addressType = userModel?.userAddrType

according to [this answer][1] i have created QRCode with string... but i. need to generate with my registered user parameters

sample Code with string:

 private func createQRFromString(str: String) -> CIImage? {
    let stringData = str.data(using: .utf8)

    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter?.setValue(stringData, forKey: "inputMessage")
    filter?.setValue("H", forKey: "inputCorrectionLevel")

    return filter?.outputImage
}

var qrCode: UIImage? {
    if let img = createQRFromString(str: "Hello world program created by someone") {
        let someImage = UIImage(
            ciImage: img,
            scale: 1.0,
            orientation: UIImage.Orientation.down
        )
        return someImage
    }

    return nil
}

@IBAction func qrcodeBtnAct(_ sender: Any) {
    
    qrImag.image = qrCode
    
}

please suggest me [1]: Is there a way to generate QR code image on iOS

Upvotes: 2

Views: 2243

Answers (1)

Rob
Rob

Reputation: 437392

You say you need a QR reader, but here you are solely talking about QR generation. Those are two different topics.

In terms of QR generation, you just need to put your four values in the QR payload. Right now you’re just passing a string literal, but you can just update that string to include your four properties in whatever easily decoded format you want.

That having been said, when writing apps like this, you often want to able to scan your QR code not only from within the app, but also any QR scanning app, such as the built in Camera app, and have it open your app. That influences how you might want to encode your payload.

The typical answer would be to make your QR code payload be a URL, using, for example, a universal link. See Supporting Universal Links in Your App. So, first focus on enabling universal links.

Once you’ve got the universal links working (not using QR codes at all, initially), the question then becomes how one would programmatically create the universal link that you’d supply to your QR generator routine, above. For that URLComponents is a great tool for encoding URLs. For example, see Swift GET request with parameters. Just use your universal link for the host used in the URL.


FWIW, while I suggest just encoding a universal link URL into your QR code, above, another option would be some other deep linking pattern, such as branch.io.

Upvotes: 3

Related Questions