京东和微博都有类似的功能:使用系统截屏功能时会弹出截图分享界面。
其实这个功能思路很简单。
第一步:注册监听截屏功能的通知,UIApplicationUserDidTakeScreenshotNotification
,如下,
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didUseScreenShot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
第二部,每次当我们截屏时self就会监听到截屏通知,并调用对应的方法做出操作。
#pragma mark 用户使用了系统截屏操作
- (void)didUseScreenShot
{
NSLog(@"用户使用了截屏操作");
if (isUseScreenShots == NO)
{
dispatch_async(dispatch_get_main_queue(), ^{
ShareView *shareView = [[ShareView alloc]initWithImage:[self getImage]];
[shareView show];
isUseScreenShots = YES;
[shareView didSelectedUseScreenShotsWithBlock:^{
isUseScreenShots = NO;
}];
});
}
}
#pragma mark 截取当前屏幕,并生成image对象
-(UIImage *)getImage
{
UIGraphicsBeginImageContext([UIScreen mainScreen].bounds.size);
[[UIApplication sharedApplication].windows[0].layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
说明:
1.
ShareView
是我自定义的弹窗界面
2.isUseScreenShots
用来判断是否已经使用截屏功能并弹出分享界面,如果已经弹出分享界面,则多次截屏时不再弹出。(这个也可以放到单例模式中也就行处理,总之就是保持弹窗的唯一性).如下代码
+ (instancetype)shareInstanceWithImage:(UIImage *)image
{
static ShareView *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[ShareView alloc]initWithImage:image];
});
return shareInstance;
}
#pragma mark 用户使用了系统截屏操作
- (void)didUseScreenShot
{
NSLog(@"用户使用了截屏操作");
dispatch_async(dispatch_get_main_queue(), ^{
[[ShareView shareInstanceWithImage:[self getImage]] show];
});
}
大致的界面效果如下:
IMG_0669.png