Byron Coetsee Byron Coetsee - 5 months ago 9
Swift Question

Savinging and generating AVMetadataMachineReadableCodeObject Swift

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

AVMetadataMachineReadableCodeObject
in Swift.

I'm using this library: https://github.com/yeahdongcn/RSBarcodes_Swift, 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
AVMetadataMachineReadableCodeObject
part as I get errors like
non-property
etc)

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

Answer

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.
Comments