Vision Framework Tutorial for iOS: Scanning Barcodes
In this Vision Framework tutorial, you’ll learn how to use your iPhone’s camera to scan QR codes and automatically open encoded URLs in Safari. By Emad Ghorbaninia.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Vision Framework Tutorial for iOS: Scanning Barcodes
20 mins
- Getting Started
- Getting Permission to Use Camera
- Starting an AVCaptureSession
- Setting Capture Session Quality
- Defining a Camera for Input
- Making an Output
- Running the Capture Session
- Vision Framework
- Vision and the Camera
- Using the Vision Framework
- Creating a Vision Request
- Vision Handler
- Vision Observation
- Adding a Confidence Score
- Using Barcode Symbology
- Opening Encoded URLs in Safari
- Setting Up Safari
- Opening Safari
- Where to Go From Here?
Using Barcode Symbology
Currently, your scanner responds to all types of barcodes. But what if you want your scanner to respond only to QR codes? Fortunately, Vision has a solution for you!
In the Vision Observation section above, you used VNBarcodeObservation
‘s confidence
to find how sure Vision is it found a barcode. Similarly, you can use VNBarcodeObservation
‘s symbology
property to check the type of symbol found in the Vision Request.
Once again, in processClassification(_:)
locate // TODO: Check for QR Code symbology and confidence score
. Then inside the guard add the following condition after the first let
clause:
potentialQRCode.symbology == .QR,
Your guard
should now look as follows:
guard
let potentialQRCode = barcode as? VNBarcodeObservation,
potentialQRCode.symbology == .QR,
potentialQRCode.confidence > 0.9
else { return }
With this new addition, you’ve added a check to ensure the barcode is of type .QR
. If the barcode is not a QR code, you ignore the request.
Build and run. Scan the sample QR code and see that your app now ignores the sample barcode.
Finally, you’ll finish up this nifty new feature by opening an encoded URL in Safari.
Opening Encoded URLs in Safari
Your barcode scanner is now complete. Of course, simply scanning and reading a barcode is only half the battle.
Your users will want to do something with the result of the scan. They did give you permission to use their camera, after all!
Often, QR codes contain URLs that point to interesting websites. When users scan the QR code, they want to go to the page at the encoded address.
In the following sections, you’ll work on doing just that.
Setting Up Safari
First, you need to add support for opening a link in a SFSafariViewController
.
Locate observationHandler(payload:)
and after // TODO: Open it in Safari
add the following:
// 1
guard
let payloadString = payload,
let url = URL(string: payloadString),
["http", "https"].contains(url.scheme?.lowercased())
else { return }
// 2
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
// 3
let safariVC = SFSafariViewController(url: url, configuration: config)
safariVC.delegate = self
present(safariVC, animated: true)
With this code, you:
- Make sure the encoded string in the QR code is a valid URL.
- Set up a new instance of
SFSafariViewController
. - Open Safari to the URL encoded in the QR code.
Next, you’ll work on triggering this function after having scanned a valid QR code.
Opening Safari
To open a URL with this function, you must tell processClassification(_:)
to use observationHandler(payload:)
if it finds a QR code.
In processClassification(_:)
, replace:
showAlert(
withTitle: potentialQRCode.symbology.rawValue,
// TODO: Check the confidence score
message: String(potentialQRCode.confidence)
with:
observationHandler(payload: potentialQRCode.payloadStringValue)
Here, instead of showing an alert when your barcode reader encounters a QR code, you open Safari to the URL encoded in the QR code.
Build and run and point your device towards the sample QR code.
Congratulations! You developed a fully-featured app that uses the iPhone’s camera to scan and read QR codes, and opens encoded URLs in Safari!
Where to Go From Here?
You can download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.
In this tutorial, you learned how to:
- Use the Vision Framework.
- Make and perform VNRequests.
- How to use SFSafariViewController.
- How to limit the kind of barcodes to scan for.
This project is only the beginning of what you can do with the Vision Framework. If you want to learn more, check out our Face Detection Tutorial Using the Vision Framework for iOS. For a more advanced challenge, check out AR Face Tracking Tutorial for iOS: Getting Started.
You can also visit the developer documentation for the Vision Framework, AVCaptureSession, VNDetectBarcodesRequest, VNBarcodeObservation, and VNBarcodeSymbology.
I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!