How to generate a barcode from a string in swift ?

Hi All,


I am developing an IOS app using Swift and Firebase. I want to generate a Barcode for each user and provide discounts to them. How can I generate a Barcode? Which Barcode scanning device is suitable?

I have googled and read, but they are not useful. Please shed some light and provide any useful link or website.

I have tried below code, but it's not generating an Barcode. I don't see any output/Barcode image. My screen was empty. Please suggest.


@IBAction func gen(_ sender: UIButton) { imageDisplay.image = generateBarcodeFromString(from: tfInput.text!) }


func generateBarcodeFromString(from string: String)-> UIImage?{ let data = string.data(using: String.Encoding.ascii) let filter = CIFilter(name: "CICode128BarcodeGenerator") filter?.setValue(data, forKey: "inputMessage") let transform = __CGAffineTransformMake(10, 10, 10, 10, 10, 10) / CGAffineTransform(scaleX: 3, y: 3)

*/

  if let output = filter?.outputImage?.applying(transform){ return UIImage(ciImage: output) } return nil }

Did you consider creating QRCode instead of barcode ? They are much more flexible.


Here are some resources about it :

for reading QRcode:

h ttp://www.appcoda.com/qr-code-reader-swift/


for generating QRCode:

h ttps://github.com/aschuch/QRCode


Edit

if you definitely need barcode, look here :

h ttps://github.com/yeahdongcn/RSBarcodes_Swift

Have you tested generating a barcode without applying a transform to determine whether the transform is causing a problem?

Hi,


I've just created a small demo, placing the barcode image via code on the scene.

ViewController.swift:

import UIKit
class ViewController: UIViewController {
   
    override func viewDidLoad() {
        super.viewDidLoad()
       
        //create barcode image
        let barCodeImage = UIImage()
        let barCode = UIImageView(image: barCodeImage)
        barCode.image = generateBarcode(from: "Having fun with Swift")
        //add barcode to the scene
        barCode.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 200)
        view.addSubview(barCode)
    }

    func generateBarcode(from string: String) -> UIImage? {
        let data = string.data(using: String.Encoding.ascii)
       
        if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
            filter.setValue(data, forKey: "inputMessage")
            if let output = filter.outputImage {
                return UIImage(ciImage: output)
            }
        }
       
        return nil
    }
}


Have fun,

Joris

How to generate a barcode from a string in swift ?
 
 
Q