iOS开发 - VisionKit 学习

1,458 阅读1分钟

首先VisionKit是一个关于文档识别的框架,可以使用摄像头拍文档,然后将文档转化为扫描件。

里面只有两个类VNDocumentCameraViewController和VNDocumentCameraScan,还有一个代理VNDocumentCameraViewControllerDelegate

使用方法如下。首先导入VisionKit框架

#import <VisionKit/VisionKit.h>

然后创建VNDocumentCameraViewController控制器。由于VisionKit框架是iOS 13推出的,因此我们要对它进行一个判断,以免低版本编译失败。

if(@available(iOS 13,*)) {

    //只有支持的机型才能使用,因此要判断是否支持

    if (!VNDocumentCameraViewController.supported) {
        UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前设备不支持!" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
        return;
    }

    VNDocumentCameraViewController* dcVc = [[VNDocumentCameraViewController alloc] init];
    dcVc.delegate=self;
    [self presentViewController:dcVc animated:YES completion:nil];

}

然后需要在info.plist文件中添加NSPhotoLibraryAddUsageDescription和NSCameraUsageDescription两个key,以免崩溃。

紧接着遵守VNDocumentCameraViewControllerDelegate代理。

#pragma mark - VNDocumentCameraViewControllerDelegate

- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller didFinishWithScan:(VNDocumentCameraScan *)scan API_AVAILABLE(ios(13)){

    for(int i = 0; i < [scan pageCount]; i++) {
        UIImage* img = [scan imageOfPageAtIndex:i];
        //此处就可以拿到扫描成功的文档图片了,此处我用到了YYKit保存图片的方法
        [img saveToAlbumWithCompletionBlock:nil];
    }

}

- (void)documentCameraViewControllerDidCancel:(VNDocumentCameraViewController *)controller API_AVAILABLE(ios(13)){

    [controller dismissViewControllerAnimated:YES  completion:nil];

}

- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller didFailWithError:(NSError *)error API_AVAILABLE(ios(13)){

}

参考文章

VNDocumentCameraViewController

使用VNDocumentCameraViewController & VNDetectBarcodesRequest 掃描 QR Code

Document Scanning and Text Recognition With Vision and VisionKit on iOS

用苹果官方 API 实现 iOS 备忘录的扫描文稿功能

Develop your own OCR on iOS 13 with VisionKit

How to detect documents using VNDocumentCameraViewController