应用场景:oOC原生webview嵌套一个H5页面,这个页面要实现截屏后保存图片到手机的功能.
流程如下:
001 OCWKWebView 需要增加一个获取H5消息的信号量
002 通过WKWebView的代理方法获取到H5发送的消息
003 根据与H5约定的类型就行截图和保存手机操作
代码如下
WKWebViewConfiguration *webViewConfigeration = [[WKWebViewConfiguration alloc]init];
webViewConfigeration.userContentController = [[WKUserContentController alloc]init];
[webViewConfigeration.userContentController addScriptMessageHandler:self name:@"原生和H5之间约定的信号量"];
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if([message.name isEqualToString:@"原生和H5之间约定的信号量"])
//进行截图保存手机相册处理
}
- (void)doScreenShot{
// 开启图片上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
// 获取当前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 截图:实际是把layer上面的东西绘制到上下文中
[self.view.layer renderInContext:ctx];
//iOS7+ 推荐使用的方法,代替上述方法
// [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
// 获取截图
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
[self saveImageAction:image];
}
-(void)saveImageAction:(UIImage *)image{
[[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
NSLog(@"%@",@"保存失败");
} else {
NSLog(@"%@",@"保存成功");
}
}];
}
参考文献:
https://developer.apple.com/documentation/webkit/wkwebview
https://www.jianshu.com/p/73b404824343
https://www.jianshu.com/p/9da1c0ceb5fa