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 相关文章推荐
js单例模式的两种方案
Oct 22 Javascript
简单易用的倒计时js代码
Aug 04 Javascript
JavaScript生成福利彩票双色球号码
May 15 Javascript
JavaScript实现Iterator模式实例分析
Jun 09 Javascript
百度地图api如何使用
Aug 03 Javascript
jQuery通过ajax快速批量提交表单数据
Oct 25 Javascript
完美解决IE不支持Data.parse()的问题
Nov 24 Javascript
Webpack 之 babel-loader文件预处理器详解
Mar 23 Javascript
layui prompt 设置允许空白提交的方法
Sep 24 Javascript
js中apply和call的理解与使用方法
Nov 27 Javascript
iSlider手机端图片滑动切换插件使用详解
Dec 24 Javascript
基于vue实现探探滑动组件功能
May 29 Javascript
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
浅析PHP的静态成员函数效率更高的原因
2014/06/13 PHP
php截取中文字符串函数实例
2015/02/23 PHP
php实现微信企业付款到个人零钱功能
2018/10/09 PHP
php高性能日志系统 seaslog 的安装与使用方法分析
2020/02/29 PHP
js类中获取外部函数名的方法
2007/08/19 Javascript
Firefox+FireBug使JQuery的学习更加轻松愉快
2010/01/01 Javascript
详谈LABJS按需动态加载js文件
2015/05/07 Javascript
分享JS代码实现鼠标放在输入框上输入框和图片同时更换样式
2016/09/01 Javascript
表单元素值获取方式js及java方式的简单实例
2016/10/15 Javascript
简单谈谈Javascript函数中的arguments
2017/02/09 Javascript
Bootstrap table使用方法总结
2017/05/10 Javascript
JS实现简易的图片拖拽排序实例代码
2017/06/09 Javascript
五步轻松实现JavaScript HTML时钟效果
2020/03/25 Javascript
详解vue.js数据传递以及数据分发slot
2018/01/20 Javascript
Vue-不允许嵌套式的渲染方法
2018/09/13 Javascript
Nginx设置为Node.js的前端服务器方法总结
2019/03/27 Javascript
vue 解决路由只变化参数页面组件不更新问题
2019/11/05 Javascript
vue 解决computed修改data数据的问题
2019/11/06 Javascript
使用python BeautifulSoup库抓取58手机维修信息
2013/11/21 Python
使用python删除nginx缓存文件示例(python文件操作)
2014/03/26 Python
Java Web开发过程中登陆模块的验证码的实现方式总结
2016/05/25 Python
Python 动态导入对象,importlib.import_module()的使用方法
2019/08/28 Python
Pytorch 图像变换函数集合小结
2021/02/01 Python
css3动画过渡实现鼠标跟随导航效果
2018/02/08 HTML / CSS
mysql的最长数据库名,表名,字段名可以是多长
2014/04/21 面试题
审计工作个人的自我评价
2013/12/25 职场文书
偷看我的初中毕业鉴定
2014/01/29 职场文书
2014年连锁店圣诞节活动方案
2014/12/09 职场文书
茶楼服务员岗位职责
2015/02/09 职场文书
个人总结怎么写
2015/02/26 职场文书
廉政承诺书范文
2015/04/28 职场文书
公司表扬稿范文
2015/05/05 职场文书
2016春季田径运动会广播稿
2015/12/21 职场文书
应届生们该怎么书写求职信?
2019/07/05 职场文书
关于mysql中时间日期类型和字符串类型的选择
2021/11/27 MySQL
angular4实现带搜索的下拉框
2022/03/25 Javascript