Membuat Scan QRCode Di Swift

QRCode kepanjangan dari Quick Response Code sering dipakai pada aplikasi desktop seperti di toko-toko atau swalayan untuk membaca kode barang sehingga dapat memudahkan dalam mengelola data transaksi secara cepat dan akurat. Mari kita belajar membuat scan QRCode menggunakan pemrograman swift. Kali ini kita akan menggunakan Library QRCodeReader.swift.

Run Project
Run Project

Buka terminal
– Buka Podfile -> open -a xcode Podfile
– Tambahkan pada Podfile -> pod ‘QRCodeReader.swift’
– Install library -> pod install
– Buat baru UIViewController dan tambahkan 1 buah UIView

UIViewController dan UIView
UIViewController dan UIView

– Pada UIView -> ubah class “QRCodeReaderView”

Class QRCodeReaderView
Class QRCodeReaderView
Class qrcodeReaderViewController
Class qrcodeReaderViewController

– Buat 1 File Cocoa Touch Class, qrcodeViewController.swift
– Kembali lagi ke main storyboard pada UIViewController -> ubah class “qrcodeViewController”
– Ketikkan code seperti berikut :

import UIKit
import AVFoundation
import QRCodeReader

class qrcodeViewController: UIViewController, QRCodeReaderViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        guard checkScanPermissions(), !reader.isRunning else { return }

            reader.didFindCode = { result in
            print("Completion with result: \(result.value) of type \(result.metadataType)")

            DispatchQueue.main.async(execute: {
                let alertController = UIAlertController(title: "QR CODE", message: result.value, preferredStyle: .alert)
                let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in }
                alertController.addAction(OKAction)
                self.present(alertController, animated: true, completion:nil)
            })
        }

        reader.startScanning()
    }

    @IBOutlet weak var previewView: QRCodeReaderView! {
        didSet {
            previewView.setupComponents(showCancelButton: false,     showSwitchCameraButton: false, showTorchButton: false, showOverlayView: true, reader: reader)
        }
    }

    lazy var reader: QRCodeReader = QRCodeReader()
    lazy var readerVC: QRCodeReaderViewController = {
    let builder = QRCodeReaderViewControllerBuilder {
        $0.reader = QRCodeReader(metadataObjectTypes: [.qr],   captureDevicePosition: .back)
        $0.showTorchButton = true
        $0.preferredStatusBarStyle = .lightContent
        $0.reader.stopScanningWhenCodeIsFound = false
    }

    return QRCodeReaderViewController(builder: builder)
    }()

    private func checkScanPermissions() -> Bool {
        do {
            return try QRCodeReader.supportsMetadataObjectTypes()
        } catch let error as NSError {
        let alert: UIAlertController

        switch error.code {
            case -11852:
            alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert)

            alert.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in
            DispatchQueue.main.async {
                if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                 UIApplication.shared.openURL(settingsURL)
                }
            }
        }))

            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
            default:
            alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        }

        present(alert, animated: true, completion: nil)
        return false
        }
    }

    @IBAction func scanInModalAction(_ sender: AnyObject) {
        guard checkScanPermissions() else { return }

        readerVC.modalPresentationStyle = .formSheet
        readerVC.delegate = self

        readerVC.completionBlock = { (result: QRCodeReaderResult?) in
        if let result = result {
            print("Completion with result: \(result.value) of type \(result.metadataType)")
        }
        }
        present(readerVC, animated: true, completion: nil)
    }

    func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
        reader.stopScanning()

        dismiss(animated: true) { [weak self] in
            let alert = UIAlertController(
            title: "QRCodeReader",
            message: String (format:"%@ (of type %@)", result.value,    result.metadataType),
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))

        self?.present(alert, animated: true, completion: nil)
        }
    }

    func reader(_ reader: QRCodeReaderViewController,   didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
        print("Switching capturing to:   \(newCaptureDevice.device.localizedName)")
    }

    func readerDidCancel(_ reader: QRCodeReaderViewController) {
        reader.stopScanning()
        dismiss(animated: true, completion: nil)
    }

}

Jangan lupa untuk menambahkan code berikut pada Info.plist untuk mengaktifkan camera.

<key>NSCameraUsageDescription</key>
<string>Camera</string>

Build / Running Project

Build / Running Project
Build / Running Project

Terima kasih. Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *