@interface B4IDocumentScanner : NSObject <VNDocumentCameraViewControllerDelegate>
@property (nonatomic, weak) UIViewController *parentVC;
@property (nonatomic, copy) NSString *eventName;
@property (nonatomic, weak) NSObject *target;
@end
@implementation B4IDocumentScanner
+ (BOOL)isAvailable {
if (@available(iOS 13.0, *)) {
return [VNDocumentCameraViewController isSupported];
}
return NO;
}
- (void)startScanningWithController:(UIViewController*)vc eventName:(NSString*)event target:(NSObject*)tgt {
if (@available(iOS 13.0, *)) {
if (![VNDocumentCameraViewController isSupported]) {
[self sendErrorEvent:@"Document scanner not supported on this device"];
return;
}
self.parentVC = vc;
self.eventName = event;
self.target = tgt;
VNDocumentCameraViewController *docCamera = [[VNDocumentCameraViewController alloc] init];
docCamera.delegate = self;
[vc presentViewController:docCamera animated:YES completion:nil];
} else {
[self sendErrorEvent:@"VisionKit requires iOS 13+"];
}
}
- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller
didFinishWithScan:(VNDocumentCameraScan *)scan API_AVAILABLE(ios(13.0)) {
NSMutableArray *images = [NSMutableArray array];
for (NSInteger i = 0; i < scan.pageCount; i++) {
[images addObject:[scan imageOfPageAtIndex:i]];
}
[controller dismissViewControllerAnimated:YES completion:^{
[self sendSuccessEvent:images];
}];
}
- (void)documentCameraViewControllerDidCancel:(VNDocumentCameraViewController *)controller API_AVAILABLE(ios(13.0)) {
[controller dismissViewControllerAnimated:YES completion:^{
[self sendCancelEvent];
}];
}
- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller
didFailWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
[controller dismissViewControllerAnimated:YES completion:^{
[self sendErrorEvent:error.localizedDescription];
}];
}
- (void)sendSuccessEvent:(NSArray*)images {
if (self.target && self.eventName && [self.target respondsToSelector:NSSelectorFromString(self.eventName)]) {
[self.target performSelector:NSSelectorFromString(self.eventName) withObject:images];
}
}
- (void)sendCancelEvent {
NSString *cancelEvent = [NSString stringWithFormat:@"%@_Cancel", self.eventName];
if (self.target && [self.target respondsToSelector:NSSelectorFromString(cancelEvent)]) {
[self.target performSelector:NSSelectorFromString(cancelEvent)];
}
}
- (void)sendErrorEvent:(NSString*)error {
NSString *errorEvent = [NSString stringWithFormat:@"%@_Error", self.eventName];
if (self.target && [self.target respondsToSelector:NSSelectorFromString(errorEvent)]) {
[self.target performSelector:NSSelectorFromString(errorEvent) withObject:error];
}
}
@end