mikebuss / MTBBarcodeScanner

A lightweight, easy-to-use barcode scanning library for iOS 8+
MIT License
1.09k stars 197 forks source link

Swift example not working #117

Closed ledikari closed 7 years ago

ledikari commented 7 years ago

error message: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to start scanning on a device with no camera. Check requestCameraPermissionWithSuccess: method before calling startScanningWithResultBlock:

mikebuss commented 7 years ago

What device are you using to test your code? Does the app have permission to access the camera according to the Settings app?

Please share the code, or a snippet if you can.

mikebuss commented 7 years ago

It looks like the error was descriptive here: the library could not see a camera on the device because the user did not grant permission in the Settings app. As the error suggests, you'll need to use requestCameraPermissionWithSuccess to ask for permission before accessing the camera. Here is an example of that:

MTBBarcodeScanner.requestCameraPermission(success: { success in
    if success {
        do {
            try self.scanner?.startScanning(resultBlock: { codes in
                if let codes = codes {
                    for code in codes {
                        let stringValue = code.stringValue!
                        print("Found code: \(stringValue)")
                    }
                }
            })
        } catch {
            NSLog("Unable to start scanning")
        }
    } else {
        UIAlertView(title: "Scanning Unavailable", message: "This app does not have permission to access the camera", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "Ok").show()
    }
})

I've added this to the Swift example to help anyone else with the same issue. The example existed in Objective-C, but was not added to the more recent Swift one. Hope this helps!

ledikari commented 7 years ago

thanks! it works now.