#import <WebKit/WebKit.h>
籤協議 WKNavigationDelegate
@property (nonatomic, strong) WKWebView *newsWebView;
(void)createView{
self.newsWebView = [[WKWebView alloc] init];
self.newsWebView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
self.newsWebView.navigationDelegate = self;
self.newsWebView.scrollView.scrollEnabled = NO;
/// 新增監聽網頁高度,,將網頁作為tableview的頭檢視
[self.newsWebView addObserver:self forKeyPath:@”scrollView.contentSize”options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@”DJWebKitContext”];
}
#pragma mark 網頁開始載入
- (void)webView:(WKWebView )webView didStartProvisionalNavigation:(WKNavigation)navigation{
}
#pragma mark 網頁載入完成
(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation)navigation{
/// 給網頁中的圖片新增點選方法
[self addImgClickJS];
}
/// 給網頁中的圖片新增點選方法
(void)addImgClickJS {
//新增圖片點選的回撥
[self.newsWebView evaluateJavaScript:@”function registerImageClickAction(){
var imgs = document.getElementsByTagName(‘img’);
for(var i=0;i<imgs.length;i++){
imgs[i].customIndex = i;
imgs[i].onclick=function(){
window.location.href=’’+this.src;
}
}
}” completionHandler:nil];
[self.newsWebView evaluateJavaScript:@”registerImageClickAction();”completionHandler:nil];
///// 所有圖片點選滑動檢視新增以下程式碼 單圖片檢視不需要新增
[self.newsWebView evaluateJavaScript:@“function getImages(){
var imgs = document.getElementsByTagName('img');
var imgScr = '';
for(var i=0;i<imgs.length;i++){
if (i == 0){
imgScr = imgs[i].src;
} else {
imgScr = imgScr +'***'+ imgs[i].src;
}
};
return imgScr;
};” completionHandler:nil];//注入js方法
[self.newsWebView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (!error) {
self.imagesArr = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:
nil;
}
}];
}
#pragma mark 監聽網頁的內容高度
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (!self.newsWebView.isLoading) {
if([keyPath isEqualToString:@"scrollView.contentSize"]){
self.newsWebView.frame = CGRectMake(0, 0, WIDTH,self.newsWebView.scrollView.contentSize.height);
self.newsTableView.tableHeaderView = self.newsWebView;
}
}
}
#pragma mark 頁面載入失敗時呼叫
- (void)webView:(WKWebView )webView didFailProvisionalNavigation:(WKNavigation)navigation {
}
#pragma mark 在傳送請求之前,決定是否跳轉
(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSString *path = [navigationAction.request.URL.absoluteStringstringByRemovingPercentEncoding];
// NSLog(@”-=-=-==-=%@”,path);
/// 主頁面載入
if ([path isEqualToString:@"about:blank"]) {
decisionHandler(WKNavigationActionPolicyAllow);
}else{
/// 圖片的點選處理
if ([path hasSuffix:@".png"]||[path hasSuffix:@".jpg"]||[pathhasSuffix:@".jpeg"]) {
//// 檢視圖片內容(pod "MWPhotoBrowser", :[Git](http://lib.csdn.net/base/git "Git知識庫") =>'<https://github.com/EvoIos/MWPhotoBrowser>.[git](http://lib.csdn.net/base/git "Git知識庫")', :commit =>'de697e101195557ddca85661ebb266fd3f10776c’
)
//// 單個圖片檢視
MWPhoto *photo = [[MWPhoto alloc] initWithURL[NSURLURLWithString:path]];
_photosBrowser = [[MWPhotoBrowser alloc] initWithPhotos:@[photo]];
/// 所有圖片滑動檢視用下面一段替換上面兩行
NSMutableArray *photoarr = [NSMutableArray array];
for (NSString *url in self.imagesArr) {
MWPhoto *photo = [[MWPhoto alloc] initWithURL:[NSURL URLWithString:url]];
[photoarr addObject:photo];
}
_photosBrowser = [[MWPhotoBrowser alloc] initWithPhotos:photoarr];
if ([self.imagesArr containsObject:path]) {
NSInteger k = [self.imagesArr indexOfObject:path];
[_photosBrowser setCurrentPhotoIndex:k];
}else{
[_photosBrowser setCurrentPhotoIndex:0];
}
UINavigationController *nan = [[UINavigationController alloc] initWithRootViewController:_photosBrowser];
_photosBrowser.navigationItem.leftBarButtonItem = [[UIBarButtonItemalloc] initWithImage:[UIImage imageNamed:@”navBack”]style:UIBarButtonItemStylePlain target:self action:@selector(PhotobackAction)];
nan.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:nan animated:YES completion:^{
}];
/// 其他網頁連線的處理
}else if ([FLGPanduanTool isWebURL:path]){
if ([path hasPrefix:@"<http://cznews.cz001.com.cn/html/wap/detail>.[PHP](http://lib.csdn.net/base/php "PHP知識庫")?pid="]) {
FLGNewsDetailViewController *detail = [[FLGNewsDetailViewControlleralloc] init];
detail.newsID = [path substringFromIndex:51];
[self.navigationController pushViewController:detail animated:YES];
}else{
//// pod 'TOWebViewController', '~> 2.2.6'
TOWebViewController *webVC = [[TOWebViewController alloc] initWithURLString:path];
UINavigationController *nan = [[UINavigationController alloc] initWithRootViewController:webVC];
nan.navigationBar.translucent = NO;
nan.navigationBar.barTintColor = baseColor;
nan.navigationBar.barStyle = UIStatusBarStyleLightContent;
[nan.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
nan.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:nan animated:YES completion:^{
}];
}
}
decisionHandler(WKNavigationActionPolicyCancel);
}
}
web的圖片點選
//這個是網頁載入完成,導航的變化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
[self addImgClickJS];
}
(void)addImgClickJS {
//獲取所以的圖片標籤
[self.wkWebView evaluateJavaScript:@”function getImages(){
var imgs = document.getElementsByTagName('img'); var imgScr = ''; for(var i=0;i<imgs.length;i++){ if (i == 0){ imgScr = imgs[i].src; } else { imgScr = imgScr +'***'+ imgs[i].src; } }; return imgScr;
};” completionHandler:nil];//注入js方法
__weak typeof(self)weakSelf = self;
[self.wkWebView evaluateJavaScript:@”getImages()” completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (!error) { NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil; NSLog(@"urlArray = %@",urlArray); weakSelf.imageUrlArr = urlArray; } else { weakSelf.imageUrlArr = nil; }
}];
//新增圖片點選的回撥
[self.wkWebView evaluateJavaScript:@”function registerImageClickAction(){
var imgs = document.getElementsByTagName('img'); for(var i=0;i<imgs.length;i++){ imgs[i].customIndex = i; imgs[i].onclick=function(){ window.location.href='image-preview-index:'+this.customIndex; } }
}” completionHandler:nil];
[self.wkWebView evaluateJavaScript:@”registerImageClickAction();” completionHandler:nil];
}
(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
// 類似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:
//預覽圖片
NSURL * url = navigationAction.request.URL;
if ([url.scheme isEqualToString:@”image-preview-index”]) {
//圖片點選回撥 NSInteger index = [[url.absoluteString substringFromIndex:[@"image-preview-index:" length]] integerValue]; NSString * imgPath = self.imageUrlArr.count > index?self.imageUrlArr[index]:nil; NSLog(@"imgPath = %@",imgPath); decisionHandler(WKNavigationActionPolicyCancel);
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
當計算高度使用監聽方法出現問題的時候(plus 機型上拉記載出現抖動) 可以換一種方法
#pragma mark 網頁載入完成
(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
[self performSelector:@selector(loadHeight) withObject:self afterDelay:1];
}
一定要在1s延時之後 才能正確獲取網頁高度
(void)loadHeight{
self.detailTableView.hidden = NO;
CGFloat height = 0.0;
[self.detailWebView sizeToFit];
height = self.detailWebView.scrollView.contentSize.height;
CGRect webFrame = self.detailWebView.frame;
webFrame.size.height = height;
self.detailWebView.frame = webFrame;
self.headView.frame = CGRectMake(0, 0, WIDTH, 90FITWIDTH+height+100FITWIDTH);
self.detailTableView.tableHeaderView = self.headView;
[self hiddenSVProgress];
}
不用延時1s的方法
[webView evaluateJavaScript:@”document.body.scrollHeight”completionHandler:^(id _Nullable result,NSError * _Nullable error){
CGFloat height = [result floatValue];
self.newsWebView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, height);
[self.delegate webViewDidFinishLoad:height cellIndex:self.indexPath];
}];
本作品採用《CC 協議》,轉載必須註明作者和本文連結