Skip to content

ios: improve exception handling #664

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions wrappers/ios/Sources/Wrapper/Reader/ZXIBarcodeReader.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//
// SPDX-License-Identifier: Apache-2.0

#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreImage/CoreImage.h>
#import "ZXIResult.h"
Expand All @@ -12,10 +13,17 @@ NS_ASSUME_NONNULL_BEGIN
@interface ZXIBarcodeReader : NSObject
@property(nonatomic, strong) ZXIDecodeHints *hints;

- (instancetype)initWithHints:(ZXIDecodeHints*)options;
- (NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image;
- (NSArray<ZXIResult *> *)readCGImage:(nonnull CGImageRef)image;
- (NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer;
-(instancetype)initWithHints:(ZXIDecodeHints*)options;

-(nullable NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image
error:(NSError *__autoreleasing _Nullable *)error;

-(nullable NSArray<ZXIResult *> *)readCGImage:(nonnull CGImageRef)image
error:(NSError *__autoreleasing _Nullable *)error;

-(nullable NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer
error:(NSError *__autoreleasing _Nullable *)error;

@end

NS_ASSUME_NONNULL_END
87 changes: 51 additions & 36 deletions wrappers/ios/Sources/Wrapper/Reader/ZXIBarcodeReader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#import "GTIN.h"
#import "ZXIFormatHelper.h"
#import "ZXIPosition+Helper.h"
#import "ZXIErrors.h"

using namespace ZXing;

Expand All @@ -17,14 +18,20 @@
}

ZXIGTIN *getGTIN(const Result &result) {
auto country = GTIN::LookupCountryIdentifier(result.text(TextMode::Plain), result.format());
auto addOn = GTIN::EanAddOn(result);
return country.empty()
? nullptr
: [[ZXIGTIN alloc]initWithCountry:stringToNSString(country)
addOn:stringToNSString(addOn)
price:stringToNSString(GTIN::Price(addOn))
issueNumber:stringToNSString(GTIN::IssueNr(addOn))];
try {
auto country = GTIN::LookupCountryIdentifier(result.text(TextMode::Plain), result.format());
auto addOn = GTIN::EanAddOn(result);
return country.empty()
? nullptr
: [[ZXIGTIN alloc]initWithCountry:stringToNSString(country)
addOn:stringToNSString(addOn)
price:stringToNSString(GTIN::Price(addOn))
issueNumber:stringToNSString(GTIN::IssueNr(addOn))];
} catch (std::exception e) {
// Because invalid GTIN data can lead to exceptions, in which case
// we don't want to discard the whole result.
return nullptr;
}
}

@interface ZXIBarcodeReader()
Expand All @@ -44,7 +51,8 @@ - (instancetype)initWithHints:(ZXIDecodeHints*)hints{
return self;
}

- (NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer {
- (NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer
error:(NSError *__autoreleasing _Nullable *)error {
OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer);

// We tried to work with all luminance based formats listed in kCVPixelFormatType
Expand All @@ -64,24 +72,26 @@ - (instancetype)initWithHints:(ZXIDecodeHints*)hints{
ImageFormat::Lum,
static_cast<int>(bytesPerRow),
0);
NSArray* results = [self readImageView:imageView];
NSArray* results = [self readImageView:imageView error:error];
CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
return results;
}

// If given pixel format is not a supported type with a luminance channel we just use the
// default method
return [self readCIImage:[[CIImage alloc] initWithCVImageBuffer:pixelBuffer]];
return [self readCIImage:[[CIImage alloc] initWithCVImageBuffer:pixelBuffer] error:error];
}

- (NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image {
- (NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image
error:(NSError *__autoreleasing _Nullable *)error {
CGImageRef cgImage = [self.ciContext createCGImage:image fromRect:image.extent];
auto results = [self readCGImage:cgImage];
auto results = [self readCGImage:cgImage error:error];
CGImageRelease(cgImage);
return results;
}

- (NSArray<ZXIResult *> *)readCGImage: (nonnull CGImageRef)image {
- (NSArray<ZXIResult *> *)readCGImage:(nonnull CGImageRef)image
error:(NSError *__autoreleasing _Nullable *)error {
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
CGFloat cols = CGImageGetWidth(image);
CGFloat rows = CGImageGetHeight(image);
Expand All @@ -104,7 +114,7 @@ - (instancetype)initWithHints:(ZXIDecodeHints*)hints{
static_cast<int>(cols),
static_cast<int>(rows),
ImageFormat::Lum);
return [self readImageView:imageView];
return [self readImageView:imageView error:error];
}

+ (DecodeHints)DecodeHintsFromZXIOptions:(ZXIDecodeHints*)hints {
Expand All @@ -126,28 +136,33 @@ + (DecodeHints)DecodeHintsFromZXIOptions:(ZXIDecodeHints*)hints {
return resultingHints;
}

- (NSArray<ZXIResult*> *)readImageView: (ImageView)imageView {
Results results = ReadBarcodes(imageView, [ZXIBarcodeReader DecodeHintsFromZXIOptions:self.hints]);

NSMutableArray* zxiResults = [NSMutableArray array];
for (auto result: results) {
[zxiResults addObject:
[[ZXIResult alloc] init:stringToNSString(result.text())
format:ZXIFormatFromBarcodeFormat(result.format())
bytes:[[NSData alloc] initWithBytes:result.bytes().data() length:result.bytes().size()]
position:[[ZXIPosition alloc]initWithPosition: result.position()]
orientation:result.orientation()
ecLevel:stringToNSString(result.ecLevel())
symbologyIdentifier:stringToNSString(result.symbologyIdentifier())
sequenceSize:result.sequenceSize()
sequenceIndex:result.sequenceIndex()
sequenceId:stringToNSString(result.sequenceId())
readerInit:result.readerInit()
lineCount:result.lineCount()
gtin:getGTIN(result)]
];
- (NSArray<ZXIResult*> *)readImageView:(ImageView)imageView
error:(NSError *__autoreleasing _Nullable *)error {
try {
Results results = ReadBarcodes(imageView, [ZXIBarcodeReader DecodeHintsFromZXIOptions:self.hints]);
NSMutableArray* zxiResults = [NSMutableArray array];
for (auto result: results) {
[zxiResults addObject:
[[ZXIResult alloc] init:stringToNSString(result.text())
format:ZXIFormatFromBarcodeFormat(result.format())
bytes:[[NSData alloc] initWithBytes:result.bytes().data() length:result.bytes().size()]
position:[[ZXIPosition alloc]initWithPosition: result.position()]
orientation:result.orientation()
ecLevel:stringToNSString(result.ecLevel())
symbologyIdentifier:stringToNSString(result.symbologyIdentifier())
sequenceSize:result.sequenceSize()
sequenceIndex:result.sequenceIndex()
sequenceId:stringToNSString(result.sequenceId())
readerInit:result.readerInit()
lineCount:result.lineCount()
gtin:getGTIN(result)]
];
}
return zxiResults;
} catch(std::exception &e) {
SetNSError(error, ZXIReaderError, e.what());
return nil;
}
return zxiResults;
}

@end
7 changes: 1 addition & 6 deletions wrappers/ios/Sources/Wrapper/Writer/ZXIBarcodeWriter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,7 @@ -(CGImageRef)encode:(std::wstring)content
BitMatrix bitMatrix = writer.encode(content, width, height);
return [self inflate:&bitMatrix];
} catch(std::exception &e) {
if (error != nil) {
const char *errorCString = e.what();
NSString *errorDescription = errorCString ? [NSString stringWithUTF8String:errorCString] : @"Unknown error";
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: errorDescription };
*error = [NSError errorWithDomain:ZXIErrorDomain code:ZXIWriterError userInfo:userInfo];
}
SetNSError(error, ZXIWriterError, e.what());
return nil;
}
}
Expand Down
6 changes: 6 additions & 0 deletions wrappers/ios/Sources/Wrapper/ZXIErrors.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ NS_ASSUME_NONNULL_BEGIN

#define ZXIErrorDomain @"ZXIErrorDomain"

typedef NS_ENUM(NSInteger, ZXIBarcodeReaderError) {
ZXIReaderError,
};

typedef NS_ENUM(NSInteger, ZXIBarcodeWriterError) {
ZXIWriterError,
};

void SetNSError(NSError *__autoreleasing _Nullable* error, NSInteger code, const char* message);

NS_ASSUME_NONNULL_END
25 changes: 25 additions & 0 deletions wrappers/ios/Sources/Wrapper/ZXIErrors.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright 2023 KURZ Digital Solutions GmbH
//
// SPDX-License-Identifier: Apache-2.0

#import "ZXIErrors.h"

void SetNSError(NSError *__autoreleasing _Nullable* error,
NSInteger code,
const char* message) {
if (error == nil) {
return;
}
NSString *errorDescription = @"Unknown C++ error";
if (message && strlen(message) > 0) {
try {
errorDescription = [NSString stringWithUTF8String: message];
} catch (NSException *exception) {
errorDescription = @"Unknown ObjC error";
}
}
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: errorDescription };
*error = [NSError errorWithDomain:ZXIErrorDomain
code:code
userInfo:userInfo];
}
2 changes: 1 addition & 1 deletion wrappers/ios/demo/demo/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
return
}
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
if let result = reader.read(imageBuffer).first {
if let result = try? reader.read(imageBuffer).first {
print("Found barcode of format", result.format.rawValue, "with text", result.text)
}
self.zxingLock.signal()
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy