1. 程式人生 > >Swift3.0二維碼掃描實現(寫一個仿支付寶二維碼掃描的效果)

Swift3.0二維碼掃描實現(寫一個仿支付寶二維碼掃描的效果)

關鍵程式碼

import AVFoundation
//獲取攝像裝置
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
    //建立輸入,輸出流
    let input = try AVCaptureDeviceInput.init(device: device)
    let output = AVCaptureMetadataOutput()
    output.rectOfInterest = CGRect(x: 0.1, y: 0, width: 0.9, height: 1
) //設定代理,並且在主執行緒重新整理 output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) //初始化連結物件 / 高質量採集率 session.canSetSessionPreset(AVCaptureSessionPresetHigh) session.addInput(input) session.addOutput(output) //先新增輸入輸出流,後設置支援的掃碼所支援的格式,不然報錯如下:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureMetadataOutput setMetadataObjectTypes:] Unsupported type found - use -availableMetadataObjectTypes'
//http://stackoverflow.com/questions/31063846/avcapturemetadataoutput-setmetadataobjecttypes-unsupported-type-found //設定掃碼支援的編碼格式 output.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code] let layer = AVCaptureVideoPreviewLayer(session: session) layer?.videoGravity = AVLayerVideoGravityResizeAspectFill layer?.frame = view.layer.bounds view.layer.insertSublayer(layer!, at: 0
) //開始捕捉 session.startRunning() } catch let error as NSError { print("errorInfo\(error.domain)") } /// 實現代理方法 extension ScanCodeController:AVCaptureMetadataOutputObjectsDelegate { func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { if metadataObjects.count > 0 { session.stopRunning() let object = metadataObjects[0] let string: String = (object as AnyObject).stringValue if let url = URL(string: string) { if UIApplication.shared.canOpenURL(url) { //去開啟地址連結 _ = self.navigationController?.popViewController(animated: true) UIApplication.shared.open(url) } else { //獲取非連結結果 let alertViewController = UIAlertController(title: "掃描結果", message: (object as AnyObject).stringValue, preferredStyle: .alert) let actionCancel = UIAlertAction(title: "退出", style: .cancel, handler: { (action) in _ = self.navigationController?.popViewController(animated: true) }) let actinSure = UIAlertAction(title: "再次掃描", style: .default, handler: { (action) in self.session.startRunning() }) alertViewController.addAction(actionCancel) alertViewController.addAction(actinSure) self.present(alertViewController, animated: true, completion: nil) } } } } }

DEMO效果

這裡寫圖片描述