Byron Coetsee Byron Coetsee - 1 year ago 68
Swift Question

Savinging and generating AVMetadataMachineReadableCodeObject Swift

I'm having some serious issues here trying to save a

in Swift.

I'm using this library:, but it has terrible documentation.

Basically, I can scan fine and can handle that scan and future scans to build a "Scan History" type screen... The problem comes in when I restart the application - my Scan History is empty (obviously). I need to save these scans locally somehow but I'm not sure how to do that.

I've tried saving the attributes of a scan but rebuilding it after app restart is proving to be just as tricky. I've tried saving them as custom objects (which would be ideal and is possible - except for the
part as I get errors like

I'm approaching the point where I think I should try something like Realm but I've never used it before.

Answer Source

You can't easily save AVMetadataMachineReadableCodeObject to Core Data, because it's not a supported type and does not conform to NSCoding. Switching to Realm won't make any difference, because it has the same restrictions (it can't just save an AVMetadataMachineReadableCodeObject). The reasons are similar-- in both cases AVMetadataMachineReadableCodeObject isn't a subclass of the appropriate type, and it's not one of the supported property types.

What you need to do depends on how exactly your scan history UI is supposed to look. Saving the AVMetadataMachineReadableCodeObject is almost certainly not the best approach, though (you might be able to add NSCoding through a Swift extension but it's probably the wrong answer even if it works). There are a couple of possibilities:

  1. Save the data represented by the scanned code instead of the code itself. You get this from the stringValue property of AVMetadataMachineReadableCodeObject. When you want to show the scan history, generate new images to display. This is straightforward using Core Image-- COQRCodeGenerator, CIAztecCodeGenerator, CICode128BarcodeGenerator, and CIPDF417BarcodeGenerator are all built in.
  2. Take a photo at the same time as you scan the image, and display the photo as the scan history entry. Include the stringValue of the scanned code in the UI so that people can see what the image represents.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download