监听用户截屏
监听用户截屏
@(iOS)
-
iOS8之前可以用
ALAssetsLibrary
-
iOS8 以后可以用
PHAsset
-
监听通知 UIApplicationUserDidTakeScreenshotNotification
- iOS8之前可以用 ALAssetsLibrary
#pragma mark - 获取最新截图
/*
#import <AssetsLibrary/AssetsLibrary.h>
*/
- (void)latestAsset:(void (^)(UIImage * _Nullable, NSError *_Nullable))block {
if (SystemVersion < 8.0) {
[self enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse/*遍历方式,逆序*/ usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
ALAssetRepresentation *repr = [result defaultRepresentation];
UIImage *img = [UIImage imageWithCGImage:[repr fullResolutionImage]];
*stop = YES;
if (block) {
block(img,nil);
}
*stop = YES;
}
}];
*stop = YES;
}
} failureBlock:^(NSError *error) {
if (error) {
if (block) {
block(nil,error);
}
}
}];
}
}
iOS8 以后可以用 PHAsset
/*
#import <Photos/PHAsset.h>
#import <Photos/PHImageManager.h>
#import <Photos/PHFetchOptions.h>
*/
/// 获取最新截图
- (void)latestPhoto:(void (^_Nullable)(UIImage * _Nullable))block {
if (SystemVersion >= 8.0) {
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHImageRequestOptions * requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.synchronous = YES;
PHFetchResult<PHAsset*> * fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult.count > 0) {
PHAsset *asset = [fetchResult objectAtIndex:0];
PHImageManager * manager = [PHImageManager defaultManager];
CGSize targetSize = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
[manager requestImageForAsset:asset
targetSize:targetSize
contentMode:PHImageContentModeAspectFit
options:requestOptions
resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result) {
if(block) {
block(result);
}
}
}];
}
}
}
本文来自博客园,作者:struggle_time,转载请注明原文链接:https://www.cnblogs.com/songliquan/p/6902567.html