1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import <EXScreenCapture/EXScreenCaptureModule.h>
4
5@interface EXScreenCaptureModule ()
6
7@property (nonatomic, weak) UMModuleRegistry *moduleRegistry;
8
9@end
10
11@implementation EXScreenCaptureModule {
12  UIView *_blockView;
13}
14
15- (instancetype)init {
16  if (self = [super init]) {
17    CGFloat boundLength = MAX([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
18    _blockView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, boundLength, boundLength)];
19    _blockView.backgroundColor = UIColor.blackColor;
20  }
21  return self;
22}
23
24UM_EXPORT_MODULE(ExpoScreenCapture);
25
26- (void)setModuleRegistry:(UMModuleRegistry *)moduleRegistry
27{
28  _moduleRegistry = moduleRegistry;
29}
30
31UM_EXPORT_METHOD_AS(preventScreenCapture,
32                    preventScreenCaptureWithResolver:(UMPromiseResolveBlock)resolve
33                    reject:(UMPromiseRejectBlock)reject)
34{
35  if (@available(iOS 11.0, *) ) {
36    // If already recording, block it
37    dispatch_async(dispatch_get_main_queue(), ^{
38      [self preventScreenRecording];
39    });
40
41    // Avoid setting duplicate observers
42    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIScreenCapturedDidChangeNotification object:nil];
43
44    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preventScreenRecording) name:UIScreenCapturedDidChangeNotification object:nil];
45  }
46
47  resolve([NSNull null]);
48}
49
50UM_EXPORT_METHOD_AS(allowScreenCapture,
51                    allowScreenCaptureWithResolver:(UMPromiseResolveBlock)resolve
52                    rejecter:(UMPromiseRejectBlock)reject)
53{
54  if (@available(iOS 11.0, *)) {
55    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIScreenCapturedDidChangeNotification object:nil];
56  }
57
58  resolve([NSNull null]);
59}
60
61- (void)preventScreenRecording {
62  if (@available(iOS 11.0, *)) {
63    BOOL isCaptured = [[UIScreen mainScreen] isCaptured];
64
65    if (isCaptured) {
66      [UIApplication.sharedApplication.keyWindow.subviews.firstObject addSubview:_blockView];
67    } else {
68      [_blockView removeFromSuperview];
69    }
70  }
71}
72
73@end
74