iOS 监听用户截屏并获取截屏图片(动态页面)
2021-05-18 本文已影响0人
时光是贼
最近有个需要,需要截取用户当前的页面,但是一般常见的方法只能截取静态页面,动态页面会导致黑屏(如视频),如果先监听用户的截屏,再拿到截屏图片就能避免这个问题,正确姿势如下:
1,添加截屏通知监听
//引用框架
#import <Photos/Photos.h>
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDidTakeScreenshot:)
name:UIApplicationUserDidTakeScreenshotNotification object:nil];
2,截屏响应
//截屏响应
- (void)userDidTakeScreenshot:(NSNotification *)notification
{
NSLog(@"检测到截屏");
//由于截屏之后图片不会立即存储到相册,所以需要延迟一些时间再做处理
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
PHAsset * asset = [self latestAsset];
PHImageManager * imageManager = [PHImageManager defaultManager];
[imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
UIImage * image = [UIImage imageWithData:imageData];
[self addVideoTaskWithImage:image];
self.isJiePing = NO;
}];
});
}
精华:监听用户截屏后,获取相册最新图片
ps:调用之前需要用户同意完全访问相册权限
//获取最新图片
- (PHAsset *)latestAsset {
// 获取所有资源的集合,并按资源的创建时间排序
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
return [assetsFetchResults firstObject];
}
//判断相册权限
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized ) {
}