2017-07-18 90 views
0

我正在研究一个由QR码阅读器组成的项目。至于输出,我希望应用程序打开网页链接,如果QR码嵌入URL。例如,当我扫描嵌入了www.google.com的二维码时,应用程序应打开Goog​​le。如何在扫描QR码后打开URL?

下面是我的代码:

class QRScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { 
    @IBOutlet var messageLabel:UILabel! 
    @IBOutlet var topbar: UIView! 

    var captureSession:AVCaptureSession? 
    var videoPreviewLayer:AVCaptureVideoPreviewLayer? 
    var qrCodeFrameView:UIView? 

    let supportedCodeTypes = [AVMetadataObjectTypeUPCECode, 
         AVMetadataObjectTypeCode39Code, 
         AVMetadataObjectTypeCode39Mod43Code, 
         AVMetadataObjectTypeCode93Code, 
         AVMetadataObjectTypeCode128Code, 
         AVMetadataObjectTypeEAN8Code, 
         AVMetadataObjectTypeEAN13Code, 
         AVMetadataObjectTypeAztecCode, 
         AVMetadataObjectTypePDF417Code, 
         AVMetadataObjectTypeQRCode] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video as the media type parameter. 
     let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 

     do { 
      // Get an instance of the AVCaptureDeviceInput class using the previous device object. 
      let input = try AVCaptureDeviceInput(device: captureDevice) 

      // Initialize the captureSession object. 
      captureSession = AVCaptureSession() 

      // Set the input device on the capture session. 
      captureSession?.addInput(input) 

      // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session. 
      let captureMetadataOutput = AVCaptureMetadataOutput() 
      captureSession?.addOutput(captureMetadataOutput) 

      // Set delegate and use the default dispatch queue to execute the call back 
      captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) 
      captureMetadataOutput.metadataObjectTypes = supportedCodeTypes 

      // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer. 
      videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
      videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill 
      videoPreviewLayer?.frame = view.layer.bounds 
      view.layer.addSublayer(videoPreviewLayer!) 

      // Start video capture. 
      captureSession?.startRunning() 

      // Move the message label and top bar to the front 
      view.bringSubview(toFront: messageLabel) 
      view.bringSubview(toFront: topbar) 

      // Initialize QR Code Frame to highlight the QR code 
      qrCodeFrameView = UIView() 

      if let qrCodeFrameView = qrCodeFrameView { 
       qrCodeFrameView.layer.borderColor = UIColor.green.cgColor 
       qrCodeFrameView.layer.borderWidth = 2 
       view.addSubview(qrCodeFrameView) 
       view.bringSubview(toFront: qrCodeFrameView) 
      } 

     } catch { 
      // If any error occurs, simply print it out and don't continue any more. 
      print(error) 
      return 
     } 
    } 

    // MARK: - AVCaptureMetadataOutputObjectsDelegate Methods 

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { 
     // Check if the metadataObjects array is not nil and it contains at least one object. 
     if metadataObjects == nil || metadataObjects.count == 0 { 
      qrCodeFrameView?.frame = CGRect.zero 
      messageLabel.text = "No QR/barcode is detected" 
      return 
     } 

     // Get the metadata object. 
     let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject 

     if supportedCodeTypes.contains(metadataObj.type) { 
      // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds 
      let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) 
      qrCodeFrameView?.frame = barCodeObject!.bounds 

      if metadataObj.stringValue != nil { 
       messageLabel.text = metadataObj.stringValue 
      } 
     } 
    } 
} 

显然,现在,它只能检测并显示在TextView中的URL。我将不胜感激任何帮助。提前致谢。

+0

然后从metadataObj.stringValue获取URL并打开它? – GeneCode

回答

0

使用该检测链路,并打开它

let string = "some other text http://www.google.com should detect the link" 

    // Do any additional setup after loading the view, typically from a nib. 
    do{ 
     let dataDetector = try NSDataDetector(types: NSTextCheckingAllTypes) 

     dataDetector.enumerateMatches(in: string, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: string.characters.count), using: { (result, matchingFlags, pointer) in 
      if(result?.resultType == .link) 
      { 
       if let url = URL(string: NSString(string: string).substring(with: (result?.range)!)) 
       { 
        if(UIApplication.shared.canOpenURL(url)) 
        { 
         if #available(iOS 10.0, *) { 
          UIApplication.shared.open(url, options: [:], completionHandler: nil) 
         } else { 
          // Fallback on earlier versions 
          UIApplication.shared.openURL(url) 
         } 
        } 
       } 
      } 
     }) 
    } 
    catch 
    { 

    } 

希望这有助于

+0

谢谢@Honey改变了 –

+0

@Kinja你试过这个答案吗? –

+0

Ermm显然我尝试了kumar一个,但现在我想要它链接到我创建的视图控制器,而不是你知道解决方案? – Kinja

0

您可以打开URL这样也可以按照@Reinier答案

我刚才编辑的代码@Kinja

// Get the metadata object. 
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject 

if supportedCodeTypes.contains(metadataObj.type) { 
    // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds 
    let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) 
    qrCodeFrameView?.frame = barCodeObject!.bounds 

    if metadataObj.stringValue != nil { 
     let url = URL(string: metadataObj.stringValue)! 
     if #available(iOS 10.0, *) { 
      UIApplication.shared.open(url, options: [:], completionHandler: nil) 
     } else { 
      UIApplication.shared.openURL(url) 
     } 
     // messageLabel.text = metadataObj.stringValue 
    } 
} 

感谢