English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ios swift3Example Code of QR Code Scanning, Generation, and Recognition with .0

Based on Swift3.0

1.scan QR code


Set scanning session, layer, and input/output

  //Set capture device
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    do
    {
      //Set device input and output
      let input = try AVCaptureDeviceInput(device: device)
      let output = AVCaptureMetadataOutput()
      output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
      //Set session
      let scanSession = AVCaptureSession()
      scanSession.canSetSessionPreset(AVCaptureSessionPresetHigh)
      if scanSession.canAddInput(input)
      {
        scanSession.addInput(input)
      }
      if scanSession.canAddOutput(output)
      {
        scanSession.addOutput(output)
      }
      //Set scanning type (QR code and bar code)
      output.metadataObjectTypes = [
      AVMetadataObjectTypeQRCode,
      AVMetadataObjectTypeCode39Code,
      AVMetadataObjectTypeCode128Code,
      AVMetadataObjectTypeCode39Mod43Code,
      AVMetadataObjectTypeEAN13Code,
      AVMetadataObjectTypeEAN8Code,
      AVMetadataObjectTypeCode93Code]
      //Preview layer
      let scanPreviewLayer = AVCaptureVideoPreviewLayer(session:scanSession)
      scanPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
      scanPreviewLayer?.frame = view.layer.bounds
      view.layer.insertSublayer(scanPreviewLayer!, at: 0)
      //Auto focus
      if (device?.isFocusModeSupported(.autoFocus))!
      {
        do { try input.device.lockForConfiguration() } catch{ }
        input.device.focusMode = .autoFocus
        input.device.unlockForConfiguration()
      }
      //Set scanning area
      NotificationCenter.default.addObserver(forName: NSNotification.Name.AVCaptureInputPortFormatDescriptionDidChange, object: nil, queue: nil, using: {[weak self] (noti) in
          output.rectOfInterest = (scanPreviewLayer&63;.metadataOutputRectOfInterest(for: self!.scanPane.frame))!
      }
      //Save session
      self.scanSession = scanSession
    }
    catch
    {
      //Camera is not available
      Tool.confirm(title: "温馨提示", message: "Camera is not available", controller: self)
      return
    }

Start scanning

    if !scanSession.isRunning
    {
      scanSession.startRunning()
    }

Scan results are in the delegate method

//Scan capture completed
extension ScanCodeViewController : AVCaptureMetadataOutputObjectsDelegate
{
  func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
  {
    //Stop scanning
    self.scanLine.layer.removeAllAnimations()
    self.scanSession!.stopRunning()
    //Play sound
    Tool.playAlertSound(sound: "noticeMusic.caf")
    //Scan completed
    if metadataObjects.count > 0
    {
      if let resultObj = metadataObjects.first as?63; AVMetadataMachineReadableCodeObject
      {
        Tool.confirm(title: "Scan Results", message: resultObj.stringValue, controller: self, handler: { (_) in
          //Continue scanning
          self.startScan()
        }
      }
    }
  }
}

2.QR code generation


Generate CGImage through filter

    //2.QR code filter
    let contentData = self.data(using: String.Encoding.utf8)8)
    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter#63.setValue(contentData, forKey: "inputMessage")
    filter#63.setValue("H", forKey: "inputCorrectionLevel")
    let ciImage = filter#63.outputImage
    //3.color filter
    let colorFilter = CIFilter(name: "CIFalseColor")
    colorFilter#63.setValue(ciImage, forKey: "inputImage")
    colorFilter#63.setValue(CIColor(cgColor: QRCodeColor.cgColor), forKey: "inputColor0")// QR code color
    colorFilter#63.setValue(CIColor(cgColor: QRCodeBgColor.cgColor), forKey: "inputColor")1)// Background color
    //4.processing
    let outImage = colorFilter!.outputImage
    let scale = QRCodeSize / outImage!.extent.size.width;
    let transform = CGAffineTransform(scaleX: scale, y: scale)
    let transformImage = colorFilter!.outputImage!.applying(transform)

Generate UIImage through CGImage

let image = UIImage(ciImage: ciImage)

Draw Logo and border

// Draw the logo
UIGraphicsBeginImageContextWithOptions(image.size, false, UIScreen.main.scale)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
//frame
let logoBorderLineImagae = QRCodeLogo.getRoundRectImage(size: logoWidth, radius: radius, borderWidth: borderLineWidth, borderColor: borderLineColor)
//border
let logoBorderImagae = logoBorderLineImagae.getRoundRectImage(size: logoWidth, radius: radius, borderWidth: boderWidth, borderColor: borderColor)
logoBorderImagae.draw(in: logoFrame)
let QRCodeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

interface encapsulation:

 /**
   1generate QR code
   - returns: Black and white QR code (size is300)
   */
  func generateQRCode() -> UIImage
    /**
   2generate QR code
   - parameter size: size
   - returns: QR code generated with size parameter, black and white
   */
   func generateQRCodeWithSize(size:CGFloat? -> UIImage
     /**
   3generate QR code
   - parameter logo: logo
   - returns: QR code generated with Logo (size:300)
   */
   func generateQRCodeWithLogo(logo:UIImage? -> UIImage
     /**
   4generate QR code
   - parameter size: size
   - parameter logo: logo
   - returns: QR code generated with size and Logo
   */
  func generateQRCode(size:CGFloat63;logo:UIImage63; -> UIImage
    /**
   5generate QR code
   - parameter size:  size
   - parameter color:  color
   - parameter bgColor: background color
   - parameter logo:  logo
   - returns: QR code with Logo and color
   */
  func generateQRCode(size:CGFloat63;color:UIColor63;bgColor:UIColor63;logo:UIImage63; -> UIImage
    /**
   6generate QR code
   - parameter size:      size
   - parameter color:      color
   - parameter bgColor:     Background color
   - parameter logo:      Icon
   - parameter radius:     Corner radius
   - parameter borderLineWidth: Line width
   - parameter borderLineColor: Line color
   - parameter boderWidth:   Border width
   - parameter borderColor:   With color
   - returns: Custom QR code
   */
  func generateQRCode(size:CGFloat63;color:UIColor63;bgColor:UIColor63;logo:UIImage63;radius:CGFloat,borderLineWidth:CGFloat63;borderLineColor:UIColor63;borderWidth:CGFloat63;borderColor:UIColor63; -> UIImage
Use
DispatchQueue.global().async {
let image = content.generateQRCodeWithLogo(logo: self.logoImageView.image)
        DispatchQueue.main.async(execute: {
          self.QRCodeImageView.image = image
        }
      }

3.recognize QR code


Through CIDetector to recognize QR code

CIDetector is used to analyze CIImage to obtain CIFeature, each CIDetector must be initialized with a probe type (NSString). This type is used to tell the probe what features to look for

1.recognize picture QR code

  func recognizeQRCode() -> String63;
  {
    let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
    let features = detector63.features(in: CoreImage.CIImage(cgImage: self.cgImage!))
    guard (features&63; .count)! > 0 else { return nil }
    let feature = features&63; .first as&63; CIQRCodeFeature
    return feature&63; .messageString
  }

Usage Example

DispatchQueue.global().async {
      let recognizeResult = self.sourceImage&63; .recognizeQRCode()
      let result = recognizeResult&63; .characters.count > 0 &63; recognizeResult: "Unable to recognize"
      DispatchQueue.main.async {
        Tool.confirm(title: "Scan Result", message: result, controller: self)
        self.activityIndicatoryView.stopAnimating()
      }
    }

The demo address of this article is:QRCode_jb51.rar

That's all for this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support the Niyao Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, nor has it been manually edited, nor does it assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending email) to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like