Xcode 6.2: Using Swift to Extend UIImage

In my last post, I created a simple utility for creating QR Codes. Although it doesn’t have the best UX, I thought I would ignore that and separate the QR Code logic from the program to make it more generalized. This was a perfect opportunity to use Swift’s extension feature which is the analog to categories in Objective-C.

The obvious class to extend is UIImage. The extension is simple. One might argue that the resizing function could be written with a completion handler as it is inĀ rajiev‘s blog entry here. The reason I didn’t is that the resizing operation happens quickly enough that there is no need to worry about threading issues. Interestingly enough, it has the information I was looking for on the Apple Developer Forums when I was trying to figure out how to resize a QR Code without interpolation so that I would always have a pixel sharp image.

I’ve already committed my code to the QRTest project on GitHub. For those that don’t want to pull the project or look on GitHub, here is the entire extension as it exists now.


import UIKit
import CoreImage

extension UIImage {

    class func qrCodeWithMessage(message: String) -> UIImage? {
        let data: NSData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
        let qrEncoder = CIFilter(name: "CIQRCodeGenerator", withInputParameters: ["inputMessage":data, "inputCorrectionLevel":"H"])
        let ciImage = qrEncoder.outputImage
        return UIImage(CIImage: ciImage)

    func scaleQRCodeWithNoInterpolation(size: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContext(CGSizeMake(size, size));
        let context = UIGraphicsGetCurrentContext();
        CGContextSetInterpolationQuality(context, kCGInterpolationNone)
        self.drawInRect(CGRectMake(0, 0, size, size))
        let image = UIGraphicsGetImageFromCurrentImageContext();
        return image


The only downside to this approach is that it is now a two step process to create and scale the QR Code. The upside is increased flexibility and cleaner (I hope) code.



Published by

David S

David Steuber

I'm the administrator of this facility.