Reputation: 36447
I want to scan QR code fetched from photos gallery. This link has something similar but didn’t helped much. I’ve implemented scan QR functionality using camera successfully. Below is code for this :
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
// lblMesage.text = QRCaptureFailedMessage
return
}
// Get the metadata object.
metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
// Here we use filter method to check if the type of metadataObj is supported
// Instead of hardcoding the AVMetadataObjectTypeQRCode, we check if the type
// can be found in the array of supported bar codes.
if supportedBarCodes.contains(metadataObj!.type) {
// if metadataObj.type == AVMetadataObjectTypeQRCode {
// 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 {
. . .
}
}
}
func scanQRFromGallery(qrcodeImg : 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("qrCodeLink is empty")
}
else{
print("message: \(qrCodeLink)")
}
}
Any help would be appreciated.
Upvotes: 1
Views: 2968
Reputation: 710
You can use this code to scan the code from the gallery photo. For additional information about the code:
import UIKit
import AVFoundation
class QRScanner: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard
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),
let features = detector.features(in: ciImage) as? [CIQRCodeFeature]
else {
print("Something went wrong")
return
}
var qrCodeLink = ""
features.forEach { feature in
if let messageString = feature.messageString {
qrCodeLink += messageString
}
}
if qrCodeLink.isEmpty {
print("qrCodeLink is empty!")
} else {
print("message: \(qrCodeLink)")
}
self.dismiss(animated: true, completion: nil)
}
}
You can read this article: Scan QR Code From Gallery Swift
Upvotes: 3