无法从图库图像扫描QR

时间:2020-07-06 16:19:45

标签: swift uiimagepickercontroller

我正在尝试制作一个QR码扫描仪,它可以在单击按钮时从图库中获取图像并显示一条消息。

我的按钮功能是:-

@IBAction func gallaryBtnEventListener(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
            pickerController.delegate = self
            pickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
            pickerController.allowsEditing = true
            self.present(pickerController, animated: true, completion: nil)
        }
        
    }

这是imagepickerCOntroller

private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let qrcodeImg = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage {
              let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])!
              let ciImage:CIImage=CIImage(image:qrcodeImg)!
              var qrCodeLink=""
    
              let features=detector.features(in: ciImage)
              for feature in features as! [CIQRCodeFeature] {
                  qrCodeLink += feature.messageString!
              }
              
              if qrCodeLink=="" {
                  print("nothing")
              }else{
                  print("message: \(qrCodeLink)")
              }
          }
          else{
             print("Something went wrong")
          }
         self.dismiss(animated: true, completion: nil)
        }

当我运行此代码时,我可以成功地从图库中选择一张图像,但是什么也不会打印。 现在,我需要有关此的帮助。还有一件事,我没有添加任何imageView。

1 个答案:

答案 0 :(得分:1)

这是因为您要为private方法UIImagePickerControllerDelegate添加imagePickerController(_:,didFinishPickingMediaWithInfo:)访问修饰符。删除方法前面的private关键字,委托将开始正常工作。另外,请勿复制/粘贴您正在使用旧版本的委托方法,这是新版本:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let qrcodeImg = info[.originalImage] as? UIImage {
        //...
    }
}