Create QR Codes with SwiftUI

Jeeva Tamilselvan
3 min readJul 22, 2020

--

QR codes -> Quick Response codes are used to store a text in an image. Normally we have seen this kinda codes in shopping malls, online stores, and many more places. Nowadays, we are scanning some weird square box shape in mobile camera for UPI transactions in many places. Those box shapes are nothing but this QR codes only.

Let’s look at how we can create our own QR codes in iOS, SwiftUI.

In order to create QR code, we need to follow below steps,

  1. Get the Text(String) which you want to create as a QR code
  2. Convert the Text into Data
  3. Create a CIFilter object (Core Image Filter)
  4. Add the data in the filter
  5. Create a CIImage object from the CIFilter object
  6. Convert the CIImage to UIImage object
  7. Convert the UIImage to Data
  8. Display Image with the Data got from the UIImage object

Step 1:

We have created a SwiftUI View QRGeneratorView and declared a @State variable for the text field. Now, we have the String value from which QR code to be generated.

Step 2:

let data = text.data(using: .ascii, allowLossyConversion: false)

Converting the text to Data

Step 3:

guard let filter = CIFilter(name: “CIQRCodeGenerator”) else { return nil }

Now, We have created the CIFilter object. CIFilter Or Core Image Filter is used to process an image. Here CIQRCodeGenerator is the filter we are going to use to create QR Codes. Apple is providing us with a number of filter options. You can check out all those filters in this link.

The logic is, we have a Data (input text). We are converting it to an image (QR code) by applying a filter (CIFilter)

Step 4:

filter.setValue(data, forKey: “inputMessage”)

Here we are attaching the data variable into the filter variable with the key “inputMessage”. The data added with the inputMessage key is going to be a QR code. For more detail check here.

Step 5:

guard let ciimage = filter.outputImage else { return nil }

Here we are fetching the CIImage object from the filter. normally this CIImage will be small in size and will be blurred if we increase the frame. So, we need to scale up the ciimage variable.

let transform = CGAffineTransform(scaleX: 10, y: 10)

let scaledCIImage = ciimage.transformed(by: transform)

Now we have scaled up the ciimage with the help of CGAffineTransform.

Step 6:

let uiimage = UIImage(ciImage: scaledCIImage)

Now, we have converted the scaledCIImage into UIImage.

Step 7:

uiimage.pngData()!

Here, we have converted the UIImage into Data using .pngData() method

Step 8:

Now, we just need to create an Image View with the data we have got in the previous step. Check out the complete code below,

Conclusion:

Let’s run the app, You will get a screen like below and you can able to create QR codes by entering text in the text field. Hope you like this.

Thank You. 🙏

--

--

Jeeva Tamilselvan
Jeeva Tamilselvan

Responses (1)