Tutorial: How to generate QR Code’s on iOS

Anup D'Souza
anupdsouza
Published in
2 min readMar 7, 2016

Using the CoreImage framework, one can easily generate QR Codes from within an iOS app with very few lines of code. Using the CoreImage filter, specifically the ‘CIQRCodeGenerator’ filter, you get a CIImage that is your QR code (a CIImage object). Sounds easy? It is. Take a look at the code below:

Start off by declaring the information that will be encapsulated in the QR code. Here, it is the url of this blog initialised as an NSString. Next, you convert this information into bytes using the NSData object (always!), pay attention to the encoding used here; NSISOLatin1StringEncoding which is the recommended encoding. The next bit is the heavy lifting made easy, create a CIFilter with name CIQRCodeGenerator as mentioned earlier & set it’s inputMessage to the NSData object. Setting the inputCorrectionLevel is optional, the default is ‘M’ out of possible L, M, Q & H modes. Finally, get the QR code image as a CIImage object from the CIFilter created previously.

The next few steps demonstrate scaling the CIImage such that optimum image quality is maintained given the dimensions of the containing image view you’d want to display the QR code image in; in this case an image view of size 240.0 x 240.0. This is required in order to prevent any possible loss of information as a result of scaling the image when displaying in say, a larger image view which may cause the scanning of this code to be inaccurate or worse still.. impossible. Thats it!

QR Code

Note that it is just as easy to generate a bar code using the ‘CICode128BarcodeGenerator’ filter as shown at the end of the code sample.

--

--