WKWebview点击图片查看大图
2017-07-14 本文已影响401人
贝勒老爷
WKWebview点击看大图
废话不说直接上代码,用运行时解决这个问题
#import <objc/runtime.h>
- (void)setMethod:(NSArray *)imgUrlArray {
objc_setAssociatedObject(self, &imgUrlArrayKey, imgUrlArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSArray *)getImgUrlArray {
return objc_getAssociatedObject(self, &imgUrlArrayKey);
}
- (NSArray *)getImageUrlByJS:(WKWebView *)wkWebView {
//js方法遍历图片添加点击事件返回图片个数 这个看你咋改
//document.getElementById(\"content\").getElementsByTagName(\"img\");\
//document.getElementsByTagName(\"img\");\
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementById(\"content\").getElementsByTagName(\"img\");\
var imgUrlStr='';\
for(var i=0;i<objs.length;i++){\
if(i==0){\
imgUrlStr=objs[i].src;\
}else{\
imgUrlStr+='#'+objs[i].src;\
}\
objs[i].onclick=function(){\
document.location=\"myweb:imageClick:\"+this.src;\
};\
};\
return imgUrlStr;\
};";
//用js获取全部图片
[wkWebView evaluateJavaScript:jsGetImages completionHandler:nil];
NSString *js2 = @"getImages()";
__block NSArray *array = [NSArray array];
[wkWebView evaluateJavaScript:js2 completionHandler:^(id Result, NSError * error) {
NSString *resurlt = [NSString stringWithFormat:@"%@",Result];
if([resurlt hasPrefix:@"#"]){
resurlt = [resurlt substringFromIndex:1];
}
array = [resurlt componentsSeparatedByString:@"#"];
[wkWebView setMethod:array];
}];
return array;
}
- (void)showBigImage:(NSURLRequest *)request
show:(UIViewController *)handleVC{
NSString *str = request.URL.absoluteString;
if ([str hasPrefix:@"myweb:imageClick:"]) {
NSString *imageUrl = [str substringFromIndex:@"myweb:imageClick:".length];
NSArray *imgUrlArr = [self getImgUrlArray];
NSInteger index = 0;
for (NSInteger i = 0; i < [imgUrlArr count]; i++) {
if([imageUrl isEqualToString:imgUrlArr[i]]){
index = i;
break;
}
}
//这个是图片的数组 [self getImgUrlArray]
}
}