I am trying to make a QR code scanner, which takes an image from the gallery on button click and show a message.
My Button function is:-
@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)
}
}
And this is the 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)
}
When I run this code I successfully can select an image from the gallery, but it's print nothing. Now I need help regarding this. One more thing, I did not add any imageView.
It's because you're adding the private
access modifier for the UIImagePickerControllerDelegate
method imagePickerController(_:,didFinishPickingMediaWithInfo:)
. Remove the private
keyword in front of the method and the delegate will start to work fine. Also, do not copy/paste the delegate methods you're using the old version, here's the newer version:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let qrcodeImg = info[.originalImage] as? UIImage {
//...
}
}