iOS 监听用户截屏并获取

集团考勤最新的意见反馈需求,参照了京东的截屏反馈。
重点就是如何监听到 用户触发了系统级的截屏,并获取到当前截屏图片。

监听到用户截屏后,有两种处理方式:

  • 方式一:模拟用户的截屏动作,用layer 去绘制当前app的window 展示的内容,然后进行图像处理(比较复杂),获得UIImage
  • 方式二:在截屏后,去访问用户相册,拿到用户相册的最后一张图片,判断是不是截屏,然后采用。

一、注册监听通知 -- userDidTakeScreenshot

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDidTakeScreenshot:)                                              
name:UIApplicationUserDidTakeScreenshotNotification object:nil];

二、监听用户截屏动作,并处理layer(方式一)

-(void)userDidTakeScreenshot:(NSNotification *)notification
{
    NSLog(@"检测到截屏");
    //人为截屏, 模拟用户截屏行为, 获取所截图片
    UIImage *image_ = [self imageWithScreenshot];
    //添加显示
    UIImageView *imgvPhoto = [[UIImageView alloc]initWithImage:image_];
    imgvPhoto.frame = CGRectMake(self.window.frame.size.width/2, self.window.frame.size.height/2, self.window.frame.size.width/2, self.window.frame.size.height/2);
    //添加边框
    CALayer * layer = [imgvPhoto layer];
    layer.borderColor = [
                         [UIColor whiteColor] CGColor];
    layer.borderWidth = 5.0f;
    //添加四个边阴影
    imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
    imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);
    imgvPhoto.layer.shadowOpacity = 0.5;
    imgvPhoto.layer.shadowRadius = 10.0;
    //添加两个边阴影
    imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
    imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);
    imgvPhoto.layer.shadowOpacity = 0.5;
    imgvPhoto.layer.shadowRadius = 2.0;
    [self.window addSubview:imgvPhoto];
}

三、处理截屏图像(方式一)

- (UIImage *)imageWithScreenshot
{
    NSData *imageData = [self dataWithScreenshotInPNGFormat];
    return [UIImage imageWithData:imageData];
}
- (NSData *)dataWithScreenshotInPNGFormat
{
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }
        else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }
        else
        {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }

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

    return UIImagePNGRepresentation(image);
}

四、方式二:获取用户最后一张图片

static NSTimeInterval const latestAssetFetchInterval = 10;

@interface AJUserPhotoFetchManager ()

@property (nonatomic, strong, nullable) NSDate *lastAssetcreationDate;
@end

static NSString * const kLastAssetcreationDateKey = @"kLastAssetcreationDateKey";
@implementation AJUserPhotoFetchManager

#pragma mark - 单例方法
static AJUserPhotoFetchManager *sharedInstance;
+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
        sharedInstance.lastAssetcreationDate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastAssetcreationDateKey];
    });
    
    return sharedInstance;
}

+ (AJUserPhotoFetchManager *)sharedUserPhotoFetchManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[AJUserPhotoFetchManager alloc]init];
        sharedInstance.lastAssetcreationDate = [[NSUserDefaults standardUserDefaults] objectForKey:kLastAssetcreationDateKey];
    });
    return sharedInstance;
}


/** 点击“+”号的时候获取相册列表,获取最新保存的一张图片。
  * 根据图片保存时间,与当前时间戳进行计算,获得间隔时间。从而判断是否是需求的时间间隔。(时间间隔自定义)
 */
- (void)fetchLatestPhotoInTimeIntervalWithCompletion:(void (^)(UIImage *result, NSDictionary *info))completion{
    // 此处不能主动获取权限,在用户同意的情况下可以去获取
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        
//        AJUserPhotoFetchManager *sharedUserPhotoFetchManager = [AJUserPhotoFetchManager sharedUserPhotoFetchManager];
        PHAsset *latestAsset = [self fetchLatestPhotoAsset];
        NSDate *nowDate = [NSDate date];
        NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:latestAsset.creationDate];// 创建时间距离的时间间隔
        if (timeInterval > latestAssetFetchInterval) { // 超出时间了
            return;
        }
        // 对一张图片10s内两次获取,虽然是同一张图片,系统回调的图片结果地址不一致。 
        // 阅读了相关博客也不建议用回调的info里面字段作判断, 所以这里采用的图片的时间戳
        if (self.lastAssetcreationDate && [self.lastAssetcreationDate compare:latestAsset.creationDate] != NSOrderedAscending) { // 上次已经获取过了
            return;
        }
        
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        [[PHImageManager defaultManager] requestImageForAsset:latestAsset targetSize:UIScreen.mainScreen.bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
            self.lastAssetcreationDate = latestAsset.creationDate;
            [[NSUserDefaults standardUserDefaults] setObject:latestAsset.creationDate forKey:kLastAssetcreationDateKey];
            completion(result, info);
        }];
    }
}

- (PHAsset *)fetchLatestPhotoAsset{

    PHFetchOptions *options = [[PHFetchOptions alloc]init];
    if (@available(iOS 9.0, *)) {
        options.fetchLimit = 1;
    }
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    return assetsFetchResults.firstObject;
}

+ (void)requestAuthorization:(void (^)(PHAuthorizationStatus))handler{
    [PHPhotoLibrary requestAuthorization:handler];
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容

  • 微信可以检测到用户截屏行为(Home + Power),并在稍后点击附加功能按钮时询问用户是否要发送刚才截屏的图片...
    像羽毛那样轻阅读 2,547评论 0 6
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,103评论 1 32
  • 最近感觉日更码字特别艰难,想想是否也去读点有关写作的书呢?于是翻到了美国作家娜塔莉·戈德堡的这本《写出我...
    Sisy阳阅读 216评论 0 4
  • 第十章---论工资与利润随劳动与资本用途不同而不同 首先讨论用途不同而产生差异的种类: 职业本身有令人愉快与不快者...
    个革马阅读 8,051评论 0 9
  • 就让灵魂失重 就让生命暗潮汹涌 你是远方的星辰 世界为你苍白失色 你的瞳孔折射出的华光溢彩 是夏娃的苹果 灵魂为你...
    仙人f阅读 196评论 4 7