Swift Generate a QRCode with SwiftUI iOS -2022 ,Generate barcode images in Swift Xcode

Generate barcode images in Swift Xcode source code-



Hi Guys,Welcome to this article Are you searching for a QR code generator now here is that the one. This post will tell you about.

How to Generate a QRCode in Swift! (SwiftUI : Xcode 11)

Demo App Overview

This demo application of this tutorial will not be complicated at all. The following screenshot will show you what to do here:


Setting Up Your Project with SwiftUI

Let’s start New Project you can see how to start to run a SwiftUI app. First, open Xcode and click on Create new Xcode project. Under iOS, choose Single View App. Name your app and fill out the text fields. However, at the bottom, make sure that the User Interface SwiftUI option is selected. If you do not select the option, Xcode will generate the storyboard file.



Now Xcode will automatically create a file for you called ContentView.swift and therefore the amazing part is that it'll show you a live preview of your code.But I want a new file QRCodeView So Project right click add New File, Save As: File name QRCodeView as shown below.


Here's a simple function that wraps up QR code generation CIFilter.qrCodeGenerator() Add the following code inside QRCodeView.

import Foundation
import SwiftUI
import CoreImage.CIFilterBuiltins

struct QRCodeView : View {
    let context = CIContext()
    let filter = CIFilter.qrCodeGenerator()
    var url : String
    var body:some View{
        Image(uiImage: genrateQRImage(_url: url))
            .interpolation(.none)
            .resizable()
            .frame(width: 200, height: 200, alignment: .center)
    }
    
    func genrateQRImage(_url:String) -> UIImage {
        let data = Data(url.utf8)
        filter.setValue(data, forKey: "inputMessage")
        if let qrCodeImage = filter.outputImage {
            if let qrCodeCGImage = context.createCGImage(qrCodeImage, from: qrCodeImage.extent){
                return UIImage(cgImage: qrCodeCGImage)
            }
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }
}

ContentView file use QRCodeView  struct as shown below.


A complete version of this code can be found on Github here.

If you would like to read more about the QR code generator or Core Image filters, inspect the Apple Documentation.

I hope this article was helpful to you. So, please share it together with your friends and colleagues using the social buttons below!

Post a Comment

0 Comments