SoFunction
Updated on 2025-04-12

iOS natively implements scanning QR codes and barcode functions to limit scanning areas

Now Apple's iOS system has natively supported the QR code scanning function. Using native scanning requires importing AVFoundation.

Scan preparation

1. Obtain camera equipment:

device = (withMediaType: AVMediaTypeVideo)

2. Create an input stream

do {
  try input = AVCaptureDeviceInput(device: device)
} catch let e as NSError {
  print()
}

3. Create output stream

output = AVCaptureMetadataOutput()
// Set the proxy to refresh in the main threadoutput?.setMetadataObjectsDelegate(self, queue: )

4. Initialize the connection object

session = AVCaptureSession()
// High quality collection ratesession?.canSetSessionPreset(AVCaptureSessionPresetHigh)
session?.addOutput(output)
session?.addInput(input)

5. Set the scan area

// Special attention: for effective scanning area, positioning is based on the set right vertex as the origin.  The line where the screen width is located is the y-axis, and the line where the screen height is located is the x-axislet x = ((SCREENHeight - QRCodeWidth - topViewHeight) / 2.0) / SCREENHeight
let y = ((SCREENWidth - QRCodeWidth) / 2.0) / SCREENWidth
let width = QRCodeWidth / SCREENHeight
let height = QRCodeWidth / SCREENWidth
output?.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)

6. Set the encoding format supported by scanning code (set the barcode and QR code compatible as follows)

output?.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]

7. Start capturing

preview = AVCaptureVideoPreviewLayer(session: session)
preview?.videoGravity = AVLayerVideoGravityResizeAspectFill
preview?.frame = 
(preview!, at: 0)
session?.startRunning()

Scan the animation

The animation here is a scan box animation that imitates Alipay

We create a new method that specializes in handling our animations.

fileprivate func scanAnimation() -> CABasicAnimation {
   let scanNetAnimation = CABasicAnimation()
    // Move along the Y axis    = ""
   // Scan the height of the box, note: Here is the opposite number of the actual height    = QRCodeWidth
    // Duration of the animation    = 1.5
   // Number of repetitions of animation    = MAXFLOAT
   return scanNetAnimation
}

Use animation:

When we create the interface, the scan box has a UIImageView, and we need to add our animation to this ImageView.

scanImageView?.(scanAnimation(), forKey: nil)

Processing after scanning

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
  if  > 0 {
    session?.stopRunning()
    let metadataObject = metadataObjects[0] as AnyObject
    let stringValue: String = 
    let vc = ()
     = stringValue
    ?.pushViewController(vc, animated: true)
  }
}

Click to process the scan result

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
  let requestURL = 
  if requestURL?.scheme == "http" || requestURL?.scheme == "https" || requestURL?.scheme == "mailto" && navigationType == .linkClicked {
//    (requestURL!, options: [:], completionHandler: nil)
    let svc = SFSafariViewController(url: requestURL!)
    (svc, animated: true, completion: nil)
  }
  return true
}

We can use

open func open(_ url: URL, options: [String : Any] = [:], completionHandler completion: ((Bool) -> )? = nil)

Open the connection in Safari. However, it is best to control the events in your own program. After iOS 9, Apple introduced the SFSafariViewController class, which can use this class to display the web pages you need to browse.

let svc = SFSafariViewController(url: requestURL!)
(svc, animated: true, completion: nil)

The above is the scan area of ​​iOS native scanning QR code and barcode functions that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!