static NSString * const htmlHeadString = @"<body style=\"word-wrap:break-word; font-family:Arial\"><head><style>img{max-width: 100%;height:auto;display:block;}</style><style>video{max-width: 100%;height:auto;display:block;}</style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no\" /></head>\<style type=\"text/css\">\tr{display:flex;border-right:1px solid #e0e0e0;border-bottom:1px solid #e0e0e0;border-top:1px solid #e0e0e0}\th{background:#f0f0f0;border-top:1px solid #e0e0e0}\td,th{flex:1;padding:5px;font-size:28rpx;border-left:1px solid #e0e0e0;word-break:break-all}</style>";
//js方法遍历图片添加点击事件 返回图片个数static NSString * const htmlJsGetImages =@"function getImages(){\var objs = document.getElementsByTagName(\"img\");\for(var i=0;i<objs.length;i++){\objs[i].onclick=function(){\document.location=\"myweb:imageClick:\"+this.src;\};\};\return objs.length;\}\function getImageRect(i){\var imgs = document.getElementsByTagName(\"img\");\var rect;\rect = imgs[i].getBoundingClientRect().left+\"::\";\rect = rect+imgs[i].getBoundingClientRect().top+\"::\";\rect = rect+imgs[i].width+\"::\";\rect = rect+imgs[i].height;\return rect;\}\function getImageData(i){\var imgs = document.getElementsByTagName(\"img\");\var img=imgs[i]; \var canvas=document.createElement(\"canvas\"); \var context=canvas.getContext(\"2d\"); \canvas.width=img.width; canvas.height=img.height; \context.drawImage(img,0,0,img.width,img.height); \return canvas.toDataURL(\"image/png\") \}\function pause() { \var audios = document.getElementsByTagName(\"audio\");\for (var i = 0; i < audios.length; i++) {\var audio = audios[i];\audio.pause();}\}\function getVideos () {\var videos = document.getElementsByTagName(\"video\");\for (var i = 0; i < videos.length; i++) {\var video = videos[i];\var url = video.src;\url = url + \"#t=1\";\video.src = url;}\}\document.documentElement.style.webkitUserSelect='none';\document.documentElement.style.webkitTouchCallout='none';\";
-(void)createWebView:(NSString *)coursewareDetail {
self.imgSrcArrayM= [selfreplaceImageUrl:ZLIFISNULL(coursewareDetail)];
NSString *htmlStr =[NSString stringWithFormat:@"%@%@",htmlHeadString,ZLIFISNULL(coursewareDetail)];
[self.webView loadHTMLString:[NSString stringWithFormat:@"
%@
",htmlStr]
baseURL:nil];
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//注入js方法
[webView evaluateJavaScript:htmlJsGetImages completionHandler:nil];
[webView evaluateJavaScript:@"getImages()" completionHandler:nil];//必须调用注入js方法
[webView evaluateJavaScript:@"getVideos()" completionHandler:nil];//必须调用注入js方法
//禁止长按 放大镜 选择文本
[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
//禁止长按 连接弹出提示框跳转
[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
}
//MARK:WKWebview 点击事件
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
@try{
//将url转换为string
decisionHandler(WKNavigationActionPolicyAllow);
NSString *requestString = navigationAction.request.URL.absoluteString;
if(requestString==nil){ return; }
//hasPrefix 判断创建的字符串内容是否以pic:字符开始
if([requestString hasPrefix:@"myweb:imageClick:"]){
// return NO;
NSString *imageUrl =[requestString substringFromIndex:@"myweb:imageClick:".length];
//预览图片
NSInteger number =[self.imgSrcArrayM indexOfObject:imageUrl];
NSString *str =[NSString stringWithFormat:@"getImageRect(%ld)",number];
WS(weakSelf);
[webView evaluateJavaScript:str completionHandler:^(idResult,NSError * error){
if(weakSelf.imgSrcArrayM.count>0){
// 图片总数
ZLPBViewController *imageBrowser =[[ZLPBViewController alloc]initWithFrame:SCREEN_BOUNDS];
imageBrowser.currentSelectedIamge =number;
imageBrowser.bigImageArray = weakSelf.imgSrcArrayM;
[imageBrowser showImages];
}
}];
}
}@catch(NSException *exception){
NSLog(@"错误信息:%@",exception);
}
}
//MARK:获得所有webview图片
- (NSMutableArray*)replaceImageUrl:(NSString*)content {
NSMutableArray * imgSrcArrayM = [NSMutableArrayarray];
// 匹配<img>标签
NSString *urlPattern = @"]+?src=[\"']?([^>'\"]+)[\"']?";
NSError*error = [NSErrornew];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlPattern options:NSRegularExpressionCaseInsensitive error:&error ];
// match
NSUInteger count = [regex numberOfMatchesInString:content options:NSMatchingReportProgress range:NSMakeRange(0, [content length])];// 匹配到的次数
if(count >0) {
NSArray* matches = [regex matchesInString:content options:NSMatchingReportCompletion range:NSMakeRange(0, [content length])];
for(NSTextCheckingResult*matchinmatches) {
NSIntegercount = [matchnumberOfRanges];// 匹配项
for(NSIntegerindex =0;index < count;index++){
NSRangehalfRange = [matchrangeAtIndex:index];
if(index ==1) {
// 图片的src属性值
NSString*urlStr = [contentsubstringWithRange:halfRange];
// 保存图片URL
[imgSrcArrayMaddObject:urlStr];
}
}
}
}
returnimgSrcArrayM;
}