更多方法交流可以家魏鑫:lixiaowu1129,一起探讨iOS相关技术!
更多方法交流可以家魏鑫:lixiaowu1129,一起探讨iOS相关技术!
一、.h文件里
#import <WebKit/WebKit.h>
@interface HtmlWKWebView : WKWebView
@property(nonatomic,strong)WKWebView * wkWebview;
@property(nonatomic,strong)UIView * headerView;
@property(nonatomic,strong)UIView * footView;
@property(nonatomic,strong)NSString * htmlString;
@property(nonatomic,strong)NSString * remoDeallocKvo;
@property(nonatomic,strong)NSString * actionJS;
@end
二、.m文件里
#import "HtmlWKWebView.h"
#import "JZAlbumViewController.h"
@interface HtmlWKWebView()<WKNavigationDelegate,UIGestureRecognizerDelegate>
@property (strong, nonatomic)NSMutableArray * mArrayUrl;
@property (strong, nonatomic) UIProgressView *progressView;
@end
@implementation HtmlWKWebView
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self createUI];
}
return self;
}
-(void)setActionJS:(NSString *)actionJS{
_actionJS = actionJS;
[self createUI];
}
-(void)setWkWebview:(WKWebView *)wkWebview{
_wkWebview = wkWebview;
self.progressView.hidden = NO;
[self.wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)setHtmlString:(NSString *)htmlString{
_htmlString = htmlString;
[self loadHTMLString:[self reSizeImageWithHTML:self.htmlString] baseURL:nil];
}
-(void)createUI{
self.scrollView.showsVerticalScrollIndicator=YES;
self.scrollView.showsHorizontalScrollIndicator=NO;
self.scrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
self.navigationDelegate = self;
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
_headerView = [[UIView alloc] init];
_headerView.backgroundColor = [UIColor whiteColor];
_headerView.userInteractionEnabled = YES;
[self.scrollView addSubview:_headerView];
_footView = [[UIView alloc] init];
_footView.frame = CGRectZero;
_footView.backgroundColor = [UIColor whiteColor];
_footView.userInteractionEnabled = YES;
_footView.hidden = YES;
[self.scrollView addSubview:_footView];
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPress.allowableMovement = 20;
longPress.minimumPressDuration = 1.0f;
longPress.delegate = self;
[self addGestureRecognizer:longPress];
if (self.actionJS.length>0) {
}else{
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapPress:)];
tap.delegate = self;
[self addGestureRecognizer:tap];
}
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progressView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 2);
self.progressView.trackTintColor = [UIColor clearColor];
self.progressView.hidden = YES;
[self.progressView setProgress:0.1 animated:YES];
[self addSubview:self.progressView];
}
- (NSString *)reSizeImageWithHTML:(NSString *)html {
return [NSString stringWithFormat:@"<p style='padding-top:%fpx;'></p><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:%fpx}</style>%@<p style='padding-bottom:%fpx;'></p>",self.headerView.frame.size.height, SCREEN_WIDTH - 15, html,self.footView.frame.size.height];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
[self evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id Result, NSError * error) {
dispatch_async(dispatch_get_main_queue(), ^{
CGFloat documentHeight = [Result doubleValue]+15.00;
if (self.htmlString.length>0) {
}else{
documentHeight = 0.0;
}
_footView.frame = CGRectMake(0, documentHeight-self.footView.frame.size.height, SCREEN_WIDTH, self.footView.frame.size.height);
_footView.hidden = NO;
});
}];
[self getImageUrlByJS:self];
[self remoViewCookies];
}
-(void)remoViewCookies{
if ([UIDevice currentDevice].systemVersion.floatValue>=9.0) {
NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
}];
}else{
NSString * libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
NSString * cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
}
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)sender{
if (sender.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [sender locationInView:self];
NSString *imgJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
[self evaluateJavaScript:imgJS completionHandler:^(id _Nullable imgUrl, NSError * _Nullable error) {
if (imgUrl) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
UIImage *image = [UIImage imageWithData:data];
if (!image) {
NSLog(@"读取图片失败");
return;
}
[AlertViewTool AlertWXSheetToolWithTitle:nil otherItemArrays:@[@"保存图片"] ShowRedindex:-1 CancelTitle:@"取消" handler:^(NSInteger index) {
if (index==0) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
});
}
}];
}
}];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if(!error){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[MBProgressHUD showSuccess:@"保存成功"];
});
}else{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[MBProgressHUD showSuccess:@"保存失败"];
});
}
}
#pragma mark - KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([object isEqual:self] && [keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
NSLog(@"网页进度:%f", newprogress);
if (newprogress == 1) {
[self.progressView setProgress:newprogress animated:YES];
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
weakSelf.progressView.hidden = YES;
[weakSelf.progressView setProgress:0 animated:NO];
});
} else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
-(void)setRemoDeallocKvo:(NSString *)remoDeallocKvo{
_remoDeallocKvo = remoDeallocKvo;
NSLog(@"移除了KVO");
[self.wkWebview removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
}
#pragma mark ========= 点击获取所有图片,并查看大图 ========================
-(void)getImageUrlByJS:(WKWebView *)wkWebView{
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[wkWebView evaluateJavaScript:jsGetImages completionHandler:nil];
NSString *jsString = @"getImages()";
[wkWebView evaluateJavaScript:jsString completionHandler:^(id Result, NSError * error) {
NSString *resurlt=[NSString stringWithFormat:@"%@",Result];
if([resurlt hasPrefix:@"+"]){
resurlt=[resurlt substringFromIndex:1];
}
NSArray * array=[resurlt componentsSeparatedByString:@"+"];
[self.mArrayUrl removeAllObjects];
[self.mArrayUrl addObjectsFromArray:array];
[self.mArrayUrl removeLastObject];
}];
}
- (void)handleTapPress:(UITapGestureRecognizer *)sender{
CGPoint touchPoint = [sender locationInView:self];
NSString *imgJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
[self evaluateJavaScript:imgJS completionHandler:^(id _Nullable imgUrl, NSError * _Nullable error) {
if (imgUrl) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
UIImage *image = [UIImage imageWithData:data];
if (!image) {
NSLog(@"读取图片失败");
return;
}
if (self.mArrayUrl.count>0) {
NSInteger currentIndex = 0;
for (int i= 0; i< self.mArrayUrl.count; i++) {
if ([imgUrl isEqual:self.mArrayUrl[i]]) {
currentIndex = i;
}
}
JZAlbumViewController *jzAlbumVC = [[JZAlbumViewController alloc]init];
jzAlbumVC.currentIndex = currentIndex;
jzAlbumVC.imgArr = self.mArrayUrl;
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:jzAlbumVC animated:NO completion:nil];
}else{
JZAlbumViewController *jzAlbumVC = [[JZAlbumViewController alloc]init];
jzAlbumVC.currentIndex = 0;
jzAlbumVC.imgArr = [NSMutableArray arrayWithArray:@[imgUrl]];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:jzAlbumVC animated:NO completion:nil];
}
}
}];
}
-(NSMutableArray *)mArrayUrl{
if (!_mArrayUrl) {
_mArrayUrl = [NSMutableArray array];
}
return _mArrayUrl;
}
#pragma mark======================WKWebView - alert不弹出(这是WKWebView相对于UIWebView的一个坑)===========================================
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text?:@"");
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
@end