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 动态选中下拉框
Nov 26 Javascript
javascript object array方法使用详解
Dec 03 Javascript
ext combobox动态加载数据库数据(附前后台)
Jun 17 Javascript
js实现多选项切换导航菜单的方法
Feb 06 Javascript
浅谈JavaScript中数组的增删改查
Jun 20 Javascript
js实现4个方向滚动的球
Mar 06 Javascript
纯原生js实现贪吃蛇游戏
Apr 16 Javascript
vue.js评论发布信息可插入QQ表情功能
Aug 08 Javascript
打通前后端构建一个Vue+Express的开发环境
Jul 17 Javascript
简单了解vue中的v-if和v-show的区别
Oct 08 Javascript
详解Angular Karma测试的持续集成实践
Nov 15 Javascript
在vue-cli3中使用axios获取本地json操作
Jul 30 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
咖啡机如何保养和日常清洁?
2021/03/03 冲泡冲煮
实用函数10
2007/11/08 PHP
利用Ffmpeg获得flv视频缩略图和视频时间的代码
2011/09/15 PHP
PHP生成制作验证码的简单实例
2016/06/12 PHP
php封装的mysqli类完整实例
2016/10/18 PHP
PHP 以POST方式提交XML、获取XML,解析XML详解及实例
2016/10/26 PHP
几行代码轻松实现PHP文件打包下载zip
2017/03/01 PHP
js将字符串转成正则表达式的实现方法
2013/11/13 Javascript
JS常用表单验证方法总结
2014/05/22 Javascript
JavaScript把数组作为堆栈使用的方法
2015/03/20 Javascript
javascript时间差插件分享
2016/07/18 Javascript
关于Vue.js 2.0的Vuex 2.0 你需要更新的知识库
2016/11/30 Javascript
js实现文字列表无缝滚动效果
2017/06/23 Javascript
vue 之 .sync 修饰符示例详解
2018/04/21 Javascript
webuploader分片上传的实现代码(前后端分离)
2018/09/10 Javascript
爬虫利器Puppeteer实战
2019/01/09 Javascript
JS实现返回上一页并刷新页面的方法分析
2019/07/16 Javascript
Python中字符编码简介、方法及使用建议
2015/01/08 Python
python数据结构学习之实现线性表的顺序
2018/09/28 Python
python爬虫URL重试机制的实现方法(python2.7以及python3.5)
2018/12/18 Python
python opencv调用笔记本摄像头
2019/08/28 Python
python列表推导式操作解析
2019/11/26 Python
Python字符串的修改方法实例
2019/12/19 Python
Jupyter Notebook打开任意文件夹操作
2020/04/14 Python
python代码实现将列表中重复元素之间的内容全部滤除
2020/05/22 Python
Muziker英国:中欧最大的音乐家商店
2020/02/05 全球购物
应用化学专业职业生涯规划书
2013/12/31 职场文书
个人合作协议书范本
2014/04/18 职场文书
中学生国旗下讲话稿
2014/04/26 职场文书
团代会开幕词
2015/01/28 职场文书
2015年乡镇发展党员工作总结
2015/03/31 职场文书
初中语文教学随笔
2015/08/15 职场文书
CSS实现多个元素在盒子内两端对齐效果
2021/03/30 HTML / CSS
Python Numpy之linspace用法说明
2021/04/17 Python
python实现简单的三子棋游戏
2022/04/28 Python
python基础之//、/与%的区别详解
2022/06/10 Python