前端之家收集整理的这篇文章主要介绍了
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)
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)
}
}
}
}
}