Hi Guyz , Hope you guyz have implemented QR Code functionality into your project on which we have discussed in my last post.
If not then visit :- https://mobikul.com/swift-qr-code-scanner-generator/
Now , after scanning and generating the code , sometimes we need to scan the code from the image in our iOS photo library. This feature doesn’t require any third party library as its available in AVFoundation.
AV Foundation is the full featured framework for working with time-based audiovisual media on iOS, macOS, watchOS and tvOS. Using AV Foundation, you can easily play, create, and edit QuickTime movies and MPEG-4 files, play HLS streams, and build powerful media functionality into your apps.
To scan a code from the image available in gallery Follow these steps:-
- import AVFoundation in your ViewController class
- Now assign UIImagePickerControllerDelegate and UINavigationControllerDelegate to get the image from gallery.
- Get your image from the image gallery and detect the QRCode using CIDetecter
CIDetecter is an image processor that identifies notable features (such as faces and barcodes) in a still image or video.
Your overall code will be :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import UIKit import AVFoundation class QRScanner:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let qrcodeImg = info[UIImagePickerControllerOriginalImage] 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) } |
Lets dive into the code we have just implemented inside the delegate function
- We have created an instance of CIDetecter of type QRCode
1 |
let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])! |
2. Converted the selected image into CIImage
1 |
let ciImage:CIImage=CIImage(image:qrcodeImg)! |
3. Detect the encoded information from the image using the detecter.
1 2 3 4 |
let features=detector.features(in: ciImage) for feature in features as! [CIQRCodeFeature] { qrCodeLink += feature.messageString! } |
4. Now the qrCodeLink is the String which represents the decoded information from the QRCode (a message or may be a url).
That all Folks , now you have the decoded information from the image containing your QRCode.
Enjoy and comment if you have any issue.
Cheers…..