vue 项目 iOS WKWebView 加载


Posted in Javascript onApril 17, 2019

1、首先让前端的同事打一个包(index.html,static文件包含css、资源文件、js等)导入项目;

:warning: 注意:

把index.html放入项目根目录下,command+n创建一个资源文件.bundle,资源文件里也的包含一份 index.html

vue 项目 iOS WKWebView 加载

vue 项目 iOS WKWebView 加载

下面开始代码:

懒加载WKWebView

引入#import <WebKit/WebKit.h> #import <WebKit/WKWebView.h>

继承 WKNavigationDelegate,WKUIDelegate,

- (WKWebView *)wkWebView{
  if (!_wkWebView) {
    //设置网页的配置文件
    WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
    //允许视频播放
    if (@available(iOS 9.0, *)) {
      Configuration.allowsAirPlayForMediaPlayback = YES;
    } else {
      // Fallback on earlier versions
    }
    // 允许在线播放
    Configuration.allowsInlineMediaPlayback = YES;
    // 允许可以与网页交互,选择视图
    Configuration.selectionGranularity = YES;
    // 关于 WKWebView 无法跳转新页面 设置
    Configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    // web内容处理池
    Configuration.processPool = [[WKProcessPool alloc] init];
    //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
    WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
    // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
    [UserContentController addScriptMessageHandler:self name:@"download"];//DownloadPolicy
    // 是否支持记忆读取
    Configuration.suppressesIncrementalRendering = YES;
    // 允许用户更改网页的设置
    Configuration.userContentController = UserContentController;
    
    _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kIs_iPhoneX? self.view.frame.size.height-34:self.view.frame.size.height) configuration:Configuration];
    _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
    // 设置代理
    _wkWebView.navigationDelegate = self;
    _wkWebView.UIDelegate = self;
    // 垂直滚动
    [_wkWebView.scrollView setShowsVerticalScrollIndicator:NO];
    _wkWebView.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, kIs_iPhoneX? self.view.frame.size.height-34:self.view.frame.size.height);
    //开启手势触摸
    _wkWebView.allowsBackForwardNavigationGestures = YES;
    // 设置 可以前进 和 后退
    //适应你设定的尺寸
    [_wkWebView sizeToFit];
    [self.view addSubview:_wkWebView];
  }
  return _wkWebView;
}

iOS 9 以后和 iOS 8 之前 加载方法不一样,做区分

- (void)viewDidLoad {
  [super viewDidLoad];
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSArray *array1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *matPath1 = [[array1 objectAtIndex:0] stringByAppendingPathComponent:@"QueHTML"];;
  if (![fileManager fileExistsAtPath:matPath1]) {
    NSString *matString = [[NSBundle mainBundle] pathForResource:@"QueHTML" ofType:@"bundle"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
      [fileManager removeItemAtPath:matPath1 error:nil];
      [fileManager copyItemAtPath:matString toPath:matPath1 error:nil];
      dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"创建完了");
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
          [self ios8Load];
        }
        else{
          [self ios9Load];
        }
      });
    });
  }
  else{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] <9.0) {
      [self ios8Load];
    }
    else{
      [self ios9Load];
    }
  }
}
- (void)ios8Load {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *path = [paths objectAtIndex:0];
  NSString *basePath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/"];
  [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"www/QueHTML/index.html"]]]]];
}
- (void)ios9Load {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *path = [paths objectAtIndex:0];
  NSString *basePath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/"];
  NSString *htmlPath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/index.html"];
  NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];
  if (@available(iOS 9.0, *)) {
    [self.wkWebView loadFileURL:fileURL allowingReadAccessToURL:[NSURL fileURLWithPath:basePath isDirectory:YES]];
  }
}

实现代理方法

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
  NSLog(@"接收到服务器跳转请求----%@",navigation);
}
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
  NSLog(@"在收到响应后,决定是否跳转---%@",navigationResponse.response.URL.absoluteString);
  //允许跳转
  decisionHandler(WKNavigationResponsePolicyAllow);
  //不允许跳转
  //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
  NSLog(@"在发送请求之前,决定是否跳转---%@",navigationAction.request.URL.absoluteString);
  //允许跳转
  decisionHandler(WKNavigationActionPolicyAllow);
  //不允许跳转
  //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  NSLog(@"页面开始加载");
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
  NSLog(@"内容开始返回");
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  NSLog(@"页面加载完成");
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
  NSLog(@"页面加载失败");
}

如果是https访问需加上一下代码

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    if ([challenge previousFailureCount] == 0) {
      NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
      completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    } else {
      completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
  } else {
   completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  }
}

总结

以上所述是小编给大家介绍的vue 项目 iOS WKWebView 加载,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Javascript 相关文章推荐
跟着JQuery API学Jquery 之三 筛选
Apr 09 Javascript
一个简单的JavaScript数据缓存系统实现代码
Oct 24 Javascript
jquery多行滚动/向左或向上滚动/响应鼠标实现思路及代码
Jan 23 Javascript
JS判断文本框内容改变事件的简单实例
Mar 07 Javascript
Egret引擎开发指南之创建项目
Sep 03 Javascript
JavaScript函数详解
Nov 17 Javascript
jQuery实现图片渐入渐出切换展示效果
Aug 15 Javascript
jquery 实现滚动条下拉时无限加载的简单实例
Jun 01 Javascript
AngularJS select设置默认值的实现方法
Aug 25 Javascript
js实现数组内数据的上移和下移的实例
Nov 14 Javascript
详解如何用模块化的方式写vuejs
Dec 16 Javascript
vue3.0实现插件封装
Dec 14 Vue.js
Vue组件间通信方法总结(父子组件、兄弟组件及祖先后代组件间)
Apr 17 #Javascript
详解vue-cli+element-ui树形表格(多级表格折腾小计)
Apr 17 #Javascript
抖音上用记事本编写爱心小程序教程
Apr 17 #Javascript
基于JS实现web端录音与播放功能
Apr 17 #Javascript
vue-cli的build的文件夹下没有dev-server.js文件配置mock数据的方法
Apr 17 #Javascript
vue component 中引入less文件报错 Module build failed
Apr 17 #Javascript
Vue项目路由刷新的实现代码
Apr 17 #Javascript
You might like
phpmyadmin 3.4 空密码登录的实现方法
2010/05/29 PHP
PHP设置图片文件上传大小的具体实现方法
2013/10/11 PHP
PHP基于自增数据如何生成不重复的随机数示例
2017/05/19 PHP
Laravel学习教程之路由模块
2017/08/18 PHP
InnerHtml和InnerText的区别分析
2009/03/13 Javascript
仅IE不支持setTimeout/setInterval函数的第三个以上参数
2011/05/25 Javascript
jQuery实现简洁的轮播图效果实例
2016/09/07 Javascript
浅谈js script标签中的预解析
2016/12/30 Javascript
Vue2几种常见开局方式详解
2017/09/09 Javascript
使用Vue 自定义文件选择器组件的实例代码
2020/03/04 Javascript
[56:45]DOTA2上海特级锦标赛D组小组赛#1 EG VS COL第一局
2016/02/28 DOTA
利用一个简单的例子窥探CPython内核的运行机制
2015/03/30 Python
python字典多键值及重复键值的使用方法(详解)
2016/10/31 Python
Python 基础之字符串string详解及实例
2017/04/01 Python
一个月入门Python爬虫学习,轻松爬取大规模数据
2018/01/03 Python
Python实现合并同一个文件夹下所有txt文件的方法示例
2018/04/26 Python
python+opencv+caffe+摄像头做目标检测的实例代码
2018/08/03 Python
解决webdriver.Chrome()报错:Message:'chromedriver' executable needs to be in Path
2019/06/12 Python
学习Django知识点分享
2019/09/11 Python
Python处理mysql特殊字符的问题
2020/03/02 Python
html5本地存储 localStorage操作使用详解
2016/09/20 HTML / CSS
HTML5 移动页面自适应手机屏幕四类方法总结
2017/08/17 HTML / CSS
美国排名第一的在线葡萄酒商店:Wine.com
2016/09/07 全球购物
世界上最大的网络主机公司:1&1
2016/10/12 全球购物
师范毕业生求职自荐信
2013/09/25 职场文书
大学毕业通用个人的求职信
2013/12/08 职场文书
手机业务员岗位职责
2013/12/13 职场文书
计算机学生的自我评价分享
2014/02/18 职场文书
党的群众路线教育实践活动对照检查材料思想汇报(党员篇)
2014/09/25 职场文书
先进个人申报材料
2014/12/30 职场文书
暂停营业通知
2015/04/25 职场文书
基层组织建设年活动总结
2015/05/09 职场文书
金砖之国观后感
2015/06/11 职场文书
2016年主题党日活动总结
2016/04/05 职场文书
python创建字典及相关管理操作
2022/04/13 Python
PyTorch中permute的使用方法
2022/04/26 Python