Vision Framework Barcode detection for iOS 11

后端 未结 3 1360
悲哀的现实
悲哀的现实 2021-01-02 12:32

I\'ve been implementing a test of the new Vision framework which Apple introduced in WWDC2017. I am specifically looking at the barcode detection - I\'ve been able to get af

相关标签:
3条回答
  • 2021-01-02 13:07

    If Apple is not going to provide a library for this, something like the following will work:

    extension CIQRCodeDescriptor {
        var bytes: Data? {
            return errorCorrectedPayload.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
                var cursor = pointer
    
                let representation = (cursor.pointee >> 4) & 0x0f
                guard representation == 4 /* byte encoding */ else { return nil }
    
                var count = (cursor.pointee << 4) & 0xf0
                cursor = cursor.successor()
                count |= (cursor.pointee >> 4) & 0x0f
    
                var out = Data(count: Int(count))
                guard count > 0 else { return out }
    
                var prev = (cursor.pointee << 4) & 0xf0
                for i in 2...errorCorrectedPayload.count {
                    if (i - 2) == count { break }
    
                    let cursor = pointer.advanced(by: Int(i))
                    let byte = cursor.pointee
                    let current = prev | ((byte >> 4) & 0x0f)
                    out[i - 2] = current
                    prev = (cursor.pointee << 4) & 0xf0
                }
                return out
            }
        }
    }
    

    And then

    String(data: descriptor.bytes!, encoding: .utf8 /* or whatever */)
    
    0 讨论(0)
  • 2021-01-02 13:27

    If you want to get the raw Data from the VNBarcodeObservation directly without it having to conform to some string encoding you can strip of the first 2 and 1/2 bytes like this, and get actual data without the QR code header.

                guard let barcode = barcodeObservation.barcodeDescriptor as? CIQRCodeDescriptor else { return }
                let errorCorrectedPayload = barcode.errorCorrectedPayload
                let payloadData = Data(bytes: zip(errorCorrectedPayload.advanced(by: 2),
                                                  errorCorrectedPayload.advanced(by: 3)).map { (byte1, byte2) in
                    return byte1 << 4 | byte2 >> 4
                })
    
    0 讨论(0)
  • 2021-01-02 13:31

    Apparently, in the iOS 11 beta 5 Apple introduced new payloadStringValue property of VNBarcodeObservation. Now you can read info from QR-code with no problems

    if let payload = barcodeObservation.payloadStringValue {
        print("payload is \(payload)")
    }
    
    0 讨论(0)
提交回复
热议问题