iOS/Objective-C

Objective-C) 캡쳐방지

Brad_Heo 2024. 6. 19. 15:07

iOS는 안드로이드처럼 캡쳐기능자체를 막지 못합니다.

iOS에서 UIApplicationUserDidTakeScreenshotNotification 로 스크린샷 액션이벤트를 받을 수 있습니다.
그래서 스크린캡쳐 시 경고 알렛을 노출시키는 방법도 꽤 괜찮은 방법입니다.

- (void)setupScreenShotObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(screenShotAction:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification
                                               object:nil];
}

- (void)screenShotAction:(NSNotification *)notification {
    NSLog(@"스크린샷");
}

하지만 직접적으로 화면을 가려야 하는 경우도 있습니다.
그럴 떈 UIView 타입의 UITextField 를 활용할 수 있습니다.

Swift에서는 extension을 만들어 사용할 수 있지만 Objective-C에서는 카테고리를 만들어 사용할 수 있습니다.

아래 코드는 Objective-C로 캡쳐방지 관련 함수 코드 입니다.

- (void)makeSecure {
    dispatch_async(dispatch_get_main_queue(), ^{
        UITextField *textField = [[UITextField alloc] init];
        textField.secureTextEntry = TRUE;
        textField.backgroundColor = [UIColor clearColor];

        [self addSubview:textField];
        // textField.translatesAutoresizingMaskIntoConstraints = NO;

        [NSLayoutConstraint activateConstraints:@[
            [textField.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
            [textField.centerXAnchor constraintEqualToAnchor:self.centerXAnchor]
        ]];

        // Remove textField's layer from its superlayer to avoid runtime error due to layer reference cycle
        [textField.layer removeFromSuperlayer];

        // Insert textField's layer at the correct position in the view hierarchy
        [self.layer.superlayer insertSublayer:textField.layer atIndex:0];
        if (textField.layer.sublayers.count > 0) {
            [[textField.layer.sublayers lastObject] addSublayer:self.layer];
        }
    });
}

참고자료

https://ios-development.tistory.com/1145?category=899471
https://stackoverflow.com/questions/76963411/enable-disable-screen-capture-in-ios