ksa_coder ksa_coder - 1 year ago 161
Swift Question

Swift - QR scanner throwing nil error

I built a QR scanner based on the tutorial here. When the app runs, I can see the scanner and when pointed at QR code, the correct text is displayed on screen. Now I want to have a button (Proceed) that will allow me to transition the text value scanned (usernameScanned) to next view controller This is not working and when I press the button, the app crashes with this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

This is the code I have where I store the text into the usernameScanned variable:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection 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 = CGRectZero
usernameLabel.text = "No barcode/QR code is detected"

// Get the metadata object.
let 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?.transformedMetadataObjectForMetadataObject(metadataObj)
qrCodeFrameView?.frame = barCodeObject!.bounds

if metadataObj.stringValue != nil {
usernameLabel.text = metadataObj.stringValue
self.usernameScanned = metadataObj.stringValue!

and this is the button proceed action:

@IBAction func proceedPressed(sender: AnyObject)

self.performSegueWithIdentifier("viewUserProfileForQR", sender: self)

Thanks for your help

Answer Source

As the code you posted is not throwing the error, try checking the view controller that you are trying to segue to once you press the button.

You may have variables that are not being instantiated, for example

var userNameProfile:String!

Within your prepareForSegue method it appears to me that you want to show the result of the scan (its a detail view after all) - so you should pass that value from VC1 to VC2 in this method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download