NHN Cloud > SDK User Guide > OCR > Credit Card (iOS)

Prerequisites

  1. Install NHN Cloud SDK.
  2. Enable [AI Service > OCR] inNHN Cloud Console.
  3. Check Appkey and SecretKey in OCR Console.


Supported Environment

NHN Cloud OCR operates in iOS 11.0 or higher.

Configuration of NHN Cloud OCR

The configuration of NHN Cloud OCR SDK for iOS is as follows.

Service Cocoapods Pod Name Framework Dependency Build Settings
OCR NHNCloudOCR NHNCloudOCR.framework * Vision.framework
* AVFoundation.framework
Mandatory NHNCloudCore
NHNCloudCommon
NHNCloudCore.framework
NHNCloudCommon.framework
OTHER_LDFLAGS = (
"-ObjC",
"-lc++"
);

Apply NHN Cloud OCR SDK to Xcode Project

1. Apply with Cococapods

  • Add Pod for NHN Cloud SDK by creating a pod file.
platform :ios, '11.0'
use_frameworks!

target '{YOUR PROJECT TARGET NAME}' do
    pod 'NHNCloudOCR'
end

2. Apply NHN Cloud SDK with with Swift Package Manager

  • Go to File > Add Packages... from XCode.
  • For the Package URL, enter 'https://github.com/nhn/nhncloud.ios.sdk' and select Add Package.
  • Select NHNCloudOCR.

swift_package_manager

Set up Project

  • Add -lc++ and -ObjC entries to Other Linker Flags in Build Settings.
    • Project Target > Build Settings > Linking > Other Linker Flags other_linker_flags

3. Apply NHN Cloud SDK by Downloading Binaries

Set up Framework

  • You can download the full iOS SDK from the NHN Cloud Downloads page.
  • Add NHNCloudOCR.framework, NHNCloudCore.framework, and NHNCloudCommon.framework, vision.framework, AVFoundation.framework to Xcode Project.
  • You can add vision.framework and AVFoundation.framework as follows. linked_vision_frameworks linked_avfoundation_frameworks linked_frameworks_ocr

Set up Project

  • Add -lc++ and -ObjC to Other Linker Flags of Build Settings.
    • Project Target > Build Settings > Linking > Other Linker Flags other_linker_flags

Initialize NHNCLOUDOCR SDK

  • Set AppKey and Secret issued from NHN Cloud Console in NHNCloudOCRConfiguration object.
  • AI Service > OCR > Document OCR > Credit Card
  • NHNCloudOCR uses an NHNCloudOCRConfiguration object as a parameter for initialization.
  • To get a permission to use camera, add the following items to info.plist.
Key : NSCameraUsageDescription
Value : [Camera Permission Request Message]

Specification for Initialization API

// Initialize
+ (void)initWithConfiguration:(NHNCloudOCRConfiguration *)configuration;

// Set Delegate
+ (void)setCreditCardRecognizerDelegate:(nullable id<NHNCloudCreditCardRecognizerDelegate>)delegate;

Specification for Delegate API

  • You can be notified of the recognition result when NHNCloudCreditCardRecognizerDelegate is registered.
  • When OCR is running, you can receive screen capture and video recording events.
  • SDK에서 제공하는 기본 화면 사용 시(NHNCloudCreditCardRecognizerViewController 상속 구현) 닫기, 확인 이벤트를 수신할 수 있습니다.
@protocol NHNCloudCreditCardRecognizerDelegate <NSObject>

// Return credit card recognition result
- (void)didDetectCreditCardInfo:(nullable NHNCloudCreditCardInfo *)cardInfo error:(nullable NSError *)error;

@optional

// Receive screen capture event
- (void)didDetectCreditCardSecurityEvent:(NHNCloudSecurityEvent)event;

// 닫기 버튼 이벤트 수신(NHNCloudCreditCardRecognizerViewController 상속 구현 시에만 수신 가능)
- (void)creditCardRecognizerViewControllerCancel;

// 확인 버튼 이벤트 수신(NHNCloudCreditCardRecognizerViewController 상속 구현 시에만 수신 가능)
- (void)creditCardRecognizerViewControllerConfirm;

@end

Set up Detected Image Return

  • NHNCloudCreditCardInfo data, which is the OCR result, can be returned together with the detected image.
    • Default is disabled.

Specification for Setting up Detected Image Return API

@interface NHNCloudOCR : NSObject
//..
+ (void)setDetectedImageReturn:(BOOL)enable;
+ (BOOL)isEnableDetectedImageReturn;
//..
@end

인식 영역 표시하기

인식 영역 반환 API

  • OCR 결과인 NHNCloudCreditCardInfo 데이터에 인식된 영역의 좌표 정보를 반환 받을 수 있습니다.
@interface NHNCloudCreditCardInfo : NSObject

// 카드 번호 인식 영역
@property(nonatomic, strong, readonly, nullable) NSArray<NSValue *> *numberBoundingBoxes;

// 유효 기간 인식 영역
@property(nonatomic, assign, readonly) CGRect validThruBoundingBox;

@end

인식 영역 ImageView에 그리기


- (void)viewDidLoad {
    [super viewDidLoad];
    // 인식된 이미지를 반환하도록 설정
    [NHNCloudOCR setDetectedImageReturn:YES];
}

// 신용카드 인식 결과 반환
- (void)didDetectCreditCardInfo:(nullable NHNCloudCreditCardInfo *)cardInfo error:(nullable NSError *)error {

    if (cardInfo.detectedImage != nil) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:cardInfo.detectedImage.image];
        imageView.contentMode = UIViewContentModeScaleAspectFit;

        UIGraphicsBeginImageContextWithOptions(imageView.frame.size, NO, 0.0);
        CGContextRef context = UIGraphicsGetCurrentContext();

        [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];

        // 카드 번호의 인식 영역을 그린다.
        for (NSValue *rectValue in cardInfo.numberBoundingBoxes) {
            CGRect scaledBoundingBox = [self dividedRect:rectValue.CGRectValue
                                                 // 디바이스의 해상도를 고려해 scale의 값만큼 좌표를 나눈다.
                                                   scale:[UIScreen mainScreen].scale];
            CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
            CGContextSetLineWidth(context, 5.0);
            CGContextStrokeRect(context, scaledBoundingBox);
        }

        CGRect scaledValidThruBoundingBox = [self dividedRect:cardInfo.validThruBoundingBox
                                                        scale:[UIScreen mainScreen].scale];
        // 유효 기간의 인식 영역을 그린다.                                                  
        CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
        CGContextSetLineWidth(context, 5.0);
        CGContextStrokeRect(context, scaledValidThruBoundingBox);

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        imageView.image = newImage;

        [self.view addSubview:imageView];
    }
}

- (CGRect)dividedRect:(CGRect)rect
                scale:(CGFloat)scale {
    return CGRectMake(rect.origin.x / scale, rect.origin.y / scale,
                      rect.size.width / scale, rect.size.height / scale);
}

Example of Initialization Process

#import <NHNCloudOCR/NHNCloudOCR.h>

@interface ViewController () <NHNCloudCreditCardRecognizerDelegate>
@end

@implementation ViewController

- (void)initializeOCR {
    // Initialize and set Delegate
    NHNCloudOCRConfiguration *configuration = [NHNCloudOCRConfiguration configurationWithAppKey:@"{AppKey}" secret:@"{Secret}"];

    // Set detected image return 
    [NHNCloudOCR setDetectedImageReturn:YES];

    // Initialize
    [NHNCloudOCR initWithConfiguration:configuration];

    // Set Delegate
    [NHNCloudOCR setCreditCardRecognizerDelegate:self];
}

// Return credit card recognition result
- (void)didDetectCreditCardInfo:(nullable NHNCloudCreditCardInfo *)cardInfo error:(nullable NSError *)error {
    NSLog(@"didDetectCreditCardInfo : cardInfo : %@", cardInfo);
    NSLog(@"didDetectCreditCardInfo : error : %@", error);
}

// Receive screen capture event
- (void)didDetectCreditCardSecurityEvent:(NHNCloudSecurityEvent)event {

    // Example of screen capture warning alert output
    if (event == NHNCloudSecurityEventScreenshot || event == NHNCloudSecurityEventScreenRecordingOn) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Capture is detected." preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];

        [self presentViewController:alert animated:YES completion:nil];
    }

    // Example of blank screen output when recording video
    if (event == NHNCloudSecurityEventScreenRecordingOn || event == NHNCloudSecurityEventScreenRecordingOff) {
        if ([[UIScreen mainScreen] isCaptured] ) {
            [[[UIApplication sharedApplication] windows] firstObject].hidden = YES;
        } else {
            [[[UIApplication sharedApplication] windows] firstObject].hidden = NO;
        }
    }
}

// 확인 버튼 이벤트 수신(NHNCloudCreditCardRecognizerViewController 상속 구현 시에만 수신 가능)
- (void)creditCardRecognizerViewControllerConfirm {
    // 신용카드 인식 결과 화면에서 확인 버튼을 눌렀을 때의 처리
}

// 닫기 버튼 이벤트 수신(NHNCloudCreditCardRecognizerViewController 상속 구현 시에만 수신 가능)
- (void)creditCardRecognizerViewControllerCancel {
    // 신용카드 인식 또는 결과 화면에서 닫기 버튼을 눌렀을 때의 처리
}

@end

Credit Card 적용 방법

NHNCloudCreditCardRecognizerViewController

1. Use Credit-Card Recognizer ViewController

  • You can easily use Credit-Card Recognizer to which the default UI is applied by connecting the Class implemented with inheritance of NHNCloudCreditCardRecognizerViewController to the ViewController of Storyboard.

2. Create Class

default_viewcontroller * Create ViewController Class that contains NHNCloudCreditCardRecognizerViewController as Subclass.

3. Connect to Storyboard

create_viewcontroller * Add ViewController to Storyboard.

custom_class * In the added ViewController, configure the class created in Custom Class.

segue_viewcontroller * Set ViewController Segue Event.

  • Set and implement Delegate.

Customizing NHNCloudCreditCardRecognizerServiceViewController

  • You can perform customizing of NHNCloudCreditCardRecognizerServiceViewController.
  • The Credit-Card guide cannot be changed because pre-defined values are used.

1. Inherit NHNCloudCreditCardRecognizerServiceViewController

  • You can perform customizing by implementing inheritance of NHNCloudCreditCardRecognizerServiceViewController.
Specification for Override Function

// 뷰가 메모리에 만들어질 때 초기 설정 및 데이터 준비 작업을 수행
- (void)viewDidLoad;

// 뷰가 화면에 나타나기 직전에 마지막 작업을 수행
- (void)viewWillAppear:(BOOL)animated;

// 뷰가 화면에서 사라지기 직전에 정리 작업을 수행
- (void)viewWillDisappear:(BOOL)animated;

// 뷰가 화면에서 완전히 사라진 후 추가적인 정리 작업을 수행
- (void)viewDidDisappear:(BOOL)animated;

// Update Custom UI
- (void)didUpdateCreditCardGuide:(CGRect)rect orientation:(NHNCloudCreditCardOrientation)orientation;

// Update UI for credit card recognition
- (void)imageDidDetect:(BOOL)detected;
Example of using Override

@interface OCRViewController : NHNCloudCreditCardRecognizerServiceViewController <NHNCloudCreditCardRecognizerDelegate>

@end

@implementation OCRViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [NHNCloudOCR setCreditCardRecognizerDelegate:self];
    // Create Custom UI
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self startRunning];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didUpdateCreditCardGuide:(CGRect)rect orientation:(NHNCloudCreditCardOrientation)orientation {
    [super didUpdateCreditCardGuide:rect orientation:orientation];

    // Update Custom UI  
}

- (void)imageDidDetect:(BOOL)detected {
    [super imageDidDetect:detected];

    // Update UI for credit card recognition
}

- (void)didDetectCreditCardInfo:(nullable NHNCloudCreditCardInfo *)cardInfo error:(nullable NSError *)error {

    NSLog(@"didDetectCreditCardInfo : cardInfo : %@", cardInfo);
    NSLog(@"didDetectCreditCardInfo : error : %@", error);
}

Use Test Environment

  • You can test OCR by using the Credit-Card guide provided to test NHNCloudOCR SDK.
  • OCR is initiated when a credit card exists in the Credit-Card guide.
    • Default value is hidden so that there is an invisible guide.
    • You can output a guide for testing by using enableTestGuide.

Specification for Credit-Card Guide

@interface NHNCloudOCRConfiguration : NSObject
- (void)enableTestGuide;
@end

Example of using Credit-Card guide

- (void)initializeOCR {
    // Initialize and set Delegate
    NHNCloudOCRConfiguration *configuration = [NHNCloudOCRConfiguration configurationWithAppKey:@"{AppKey}" secret:@"{Secret}" ];

    [configuration enableTestGuide];

    [NHNCloudOCR initWithConfiguration:configuration];

    [NHNCloudOCR setCreditCardRecognizerDelegate:self];
}

Control Credit-Card Recognizer ViewController

Credit Card 적용 방법을 보고 NHNCloudCreditCardRecognizerViewController 또는 NHNCloudCreditCardRecognizerServiceViewController 상속 구현 필요

1. Credit-Card Recognizer Initiate/Stop

  • Initiate or stop Credit-Card Recognizer.

Specification for Initiate/Stop Credit-Card Recognizer.

- (void)startRunning;
- (void)stopRunning;
- (BOOL)isRunning;

Example of initiate or stop Credit-Card Recognizer


- (void)start {
  [self startRunning];
}

// Return the credit card recognition result
- (void)didDetectCreditCardInfo:(nullable NHNCloudCreditCardInfo *)cardInfo error:(nullable NSError *)error {
    [self stopRunning];
}

2. Rotate Credit-Card Guide

  • You can rotate the Credit-Card guide according to the direction of a credit card.

Specification for Rotate Credit-Card Guide

@property (assign, nonatomic, readonly) CGRect creditCardGuide;
@property (assign, nonatomic, readonly) NHNCloudCreditCardOrientation creditCardGuideOrientation;
- (void)rotateCreditCardGuideOrientation;

Example of using Rotate Credit-Card Guide

typedef NS_ENUM(NSInteger, NHNCloudCreditCardOrientation) {

    NHNCloudCreditCardOrientationPortrait = 0,
    NHNCloudCreditCardOrientationLandscape = 1
};

- (void)rotateButtonAction:(UIButton *)button {

    [self rotateCreditCardGuideOrientation];

    NSLog(@"x: %f y: %f width: %f height: %f", self.creditCardGuide.origin.x,
          self.creditCardGuide.origin.y,
          self.creditCardGuide.size.width,
          self.creditCardGuide.size.height);

    NSLog(@"creditCardGuideOrientation: %ld", self.creditCardGuideOrientation);
}

3. Enable/Disable Light

  • Enable or disable the camera light of a device.

Specification for Enable/Disable Light API

- (void)enableTorchMode;
- (void)disableTorchMode;
- (BOOL)isEnableTorchMode;

Example of enabling or disabling the camera light of a device.

- (void)torchButtonAction:(UIButton *)button {    
    if ([self isEnableTorchMode] == YES) {
        [self disableTorchMode];
    } else {
        [self enableTorchMode];
    }
}

4. Enable/Disable Camera

  • Enable or disable a device’s camera.

Specification for Enable/Disable Camera

- (void)startRunningCamera;
- (void)stopRunningCamera;
- (BOOL)isRunnginCamera;

Example of enabling or disabling camera

- (void)cameraButtonAction:(UIButton *)button {    
    if ([self isRunnginCamera] == YES) {
        [self stopRunningCamera];
    } else {
        [self startRunningCamera];
    }
}

TOP