您的位置:新葡亰496net > 奥门新萄京娱乐场 > 带你走进WKWebView的世界,剖析Android中webview和js之

带你走进WKWebView的世界,剖析Android中webview和js之

发布时间:2019-06-21 12:45编辑:奥门新萄京娱乐场浏览(154)

    如同是macOS10.10自此,以及iOS8自此,新出现的WKWebview组件就急迅的代表了Webview及UIWebView。后者的确存在部分无法消除的bug,诸如架构导致的快慢迟滞和内部存款和储蓄器泄漏。
    但无能为力幸免的主题材料连连有些,比方有个别客户端软件,仍旧须要合营老版本的种类,那时候,很不想行使,但也只能依然把Webview塞到本人的代码中。
    互连网是个喜新厌旧的小圈子,网络寻找,大概唯有两类。一是WKWebview的文书档案,二是iOS类的文档。想要的macOS上边Webview的材料缈如黄鹤。
    带你走进WKWebView的世界,剖析Android中webview和js之间的并行。经过部分只言片语的素材指引和大度的尝试,终于形成了专门的学业。所以决定来烧烧冷灶,写出来记录一下。

    1.android中利用webview调用网页上的js代码。 Android 中能够透过webview来兑现和js的相互,在先后中调用js代码,只须求将webview控件的帮忙js的天性设置为true,,然后经过loadUrl就足以一直开始展览调用,如下所示:
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("javascript:test()");

    经过学习,你将会学习以下多少个方面包车型地铁剧情:

    微信iOS客户端将于二零一七年110月1近期逐步晋级为WKWebview内核,供给网页开辟者提前做好网址的分外检查和适配。

    1、WKWebview加多手势

    1.添加Webview

    最简易增添webview的点子正是直接在Interface Builder中把Webview拖入到窗口同期用鼠标拖动到钦定地点和点名大小,随后在程序中加上对应的变量:

        @IBOutlet weak var webView: WebView!
    

    借使非得动态程序完结,能够动用window.contentView?.addSubview(webView)把webview控件插入到分界面中。

    2. 网页上调用android中java代码的办法 在网页中调用java代码,需求在webview控件中增多javascriptInterface。如下所示:

    • **怎样是WKWebView以及它和UIWebView的差别是何许 **
    • **认知SafariServices.framework框架,捎带认知UIActivity **
    • 回想UIWebView在公司工程中的使用
    • WKKit 和 WKWebView简要介绍,天性认知API
    • UIWebView 和WKWebview 以及JSCore JS和OC的互相调用
    • NSURLProtocal的使用
    • WKWebView的片段坑

    背景

    WKWebView 是苹果在iOS 第88中学引进的新组件,目标是提供贰个今世的支撑最新Webkit作用的网页浏览控件,摆脱过去 UIWebView的老、旧、笨,特别是内部存款和储蓄器占用量巨大的标题。它选择与Safari中一致的Nitro JavaScript外燃机,大大提升了页面js推行进程。

    UISwipeGestureRecognizer *swipe =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction)];swipe.delegate = self;[wkWebView addGestureRecognizer:swipe];// 允许多个手势并发- gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES;}
    

    2.载入网页

    1. 可以直接导向到有些网页,也足以先在地头运维七个静态页面文件,后续一些干活可以在本土静态网页中用js管理。这种方法是比较多用的,因为程序运转速度会深感快的好多。
            let path = Bundle.main.path(forResource: "somepage", ofType: "html")
            let url = NSURL.fileURL(withPath: path!)
            let request = URLRequest(url: url);
            self.webView.mainFrame.load(request);
    
    1. 把somepage.html增多到项目,并在项目安装中Build Phases->Copy Bundle Resources中增添上文件somepage.html,那样结尾生成app文件的时候,somepage.html文件才会被打包到内部。
    2. 即使创建的品类利用沙箱(sandbox)情势,以后的运用,固然想上App Store,一般是挟持须要利用沙箱的,必要在系统设置的Capabilities中允许incoming network/output networking。不然本地网页没难点,之后的其余网站都不只怕访问。
    3. 新本子的macOS及iOS都强制必须运用https网页访问,要是急需辅助老的http网页,还亟需在Info.plist中加进一行:App Transport Security Settings,类型为字典项,在那之中扩张一项:Allow Arbitrary Loads,值为YES。
      成功以上4项,网页已经得以访问了。

    复制代码 代码如下:

    文章结构目录

    切换形式

    iOS微信6.5.3版本开端辅助开荒者手动切换WKWebview和UIWebview,使开荒者可提早对WKWebview实行适配。

     

    手动切换入口:

    在微信会话列表页点击右上角“加号开关”,选用菜单中的”加多朋友”,在增多朋友分界面的检索框中输入字符串:“:switchweb”,再点击键盘右下角找出开关。切换来功后会提醒当前选拔的内核是UIWebview或是WKWebview。

     

    校验切换情势:

    经过命令成功切换成WKWebview后,可经过以下措施求证当前网页使用的是不是是WKWebview内核。 

    微信内随机入口进去大肆网页,在网页加载成功后向下推动页面(或点击网页右上角菜单按键),使之展现出地址栏,当地址栏以 “此网页由” 开端即为当前采纳WKWebview,若以“网页由”则是利用的UIWebview。

     

    页面怎么判定当前利用的webview内核:

    在页面中可通过微信注入的window.__wxjs_is_wkwebview变量判别当前利用的webview内核。 iOS微信6.5.3会同之后的版本 window.__新葡亰496net,wxjs_is_wkwebview 为true时是使用WKWebview,为 false只怕 “undefine”时是 UIWebview 。

    前者适配关怀的中央

    适配的根本条件:若不可能分别是WKWebview的新特点新表现依然微信内部逻辑导致原来页面出现难点时,可接纳测试页面分别在Safari和微信中的WKWebview内核分别测试,用以快速定位难点爆发的因由。

    2、WKWebview禁用弹簧滑动

    3.从swift调用js

    倘诺在网页中有如下内容:

    <script>
    function callFromSwift(msg){
        document.getElementById('msgbox').innerHTML=msg;
        return("msg return from js");
    }
    </script>
    <div id='msgbox'></div>
    

    内部定义了二个函数callFromSwift,当被调用的时候,在上边预订义的div中显示传入的字符串,并且再次回到三个字符串“msg return from js”。
    在swift中调用网页中的callFrom斯维夫特函数并获取其再次回到值能够这么做:

            let s=webView.windowScriptObject.evaluateWebScript("callFromSwift('Hello, JavaScript')")
            NSLog(s as! String) //s是js函数的返回结果,可以是多种类型,本例要求是string
    

    mWebView.addJavascriptInterface(new Object() {
                public void clickOnAndroid() {
                    mHandler.post(new Runnable() {
                        public void run() {
                            Toast.makeText(Test.this, "测试调用java", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }, "demo");

    1.背景

    适配指南

    切换为WKWebview后,微信中的Webview行为和Safari中维系中度一致,唯一的分别是微信Webview中会注入微信JSBridge相关的本子。所以适配的机要须要关爱之下多少个方面: 

    一:页面效果是或不是符合规律 

    二:页面显示屏适配是还是不是寻常三:页面行为是还是不是健康(举例用户在浏览页面时点击重临开关重返上四个页面时的页面逻辑是还是不是健康) 

    四:页面使用的语法是或不是合营。 

    五:JSSAPI是还是不是平日完美的办事。 

    六:入眼关切Cookie和LocalStorage等连锁的逻辑是否正常。 

    七:若服务器有设置重返Cache-Control缓存有效时间,则须求检查不毫不相关系逻辑是还是不是正规。

     

    常规状态下,你的页面是无需做特别的适配,但若你的页面有关系到以下多少个受影响的逻辑,则要求遵照适配提议进行适配和分明。

     

    JSAPI相关适配

    一:将不再协理cache 

    变迁:在WKWebview准将暂不帮忙cache jsapi。 

    适配提出:全部应用此api的开荒者可去掉页面相关逻辑。

     

    二:页面通过LocalID预览图片 

    扭转:不再支持通过动用chooseImage api再次回到的localld以如:”img src=wxLocalResource://50114659二零一二32”的法子预览图片。 

    适配提议:

    1. 在iOS微信6.5.3版本及然后的本子中,使用新添的jsapi:getLocalImgData 得到LocalID对应的图片base64编码后再在前者页面中显得。

    2. 即使引进了页面有引进JSSDK,则向来将JSSDK晋级为1.2.0新式版本就可以扶助页面自动适配。(方今JSSDk线上版本是 1.0.0 和 1.1.0,更新版本为1.2.0 ,  )

     

    三:有应用JSSDK,并且采用了wx.config进行权力授权需关心jsapi调用的败诉难点 

    扭转:WKWebview的里边贯彻转移使大家对微信内的页面jsapi权限管理做了必然逻辑上的调动,有比十分的小莫不会产生原先授权寻常的jsapi获取权力不正规,从而产生调用jsapi退步。 

    适配建议:

    1. iOS微信6.5.1,WKWebview在此版本中已知有以下难题:页面使用HTML5的History API pushState; popstate;      replaceState等调整页面导航(规范的如单运用页面),同一时候选择JSSDK的wx.config为jsapi授权,此时大概率会晤世jsapi因为无权力而调用战败的标题。 在6.5.第11中学页面若只怕的状态下,可利用Anchor hash技能替换History本领来减轻此主题素材。

    2. iOS微信6.5.2会同之后版本,将不会设有上述难题,但不能够百分百显著有使用到 history或hash技艺改换页面导航地址的页面完全未有此类难点,仍然亟待开辟者注意关怀此类主题材料。

     

    Cookie和LocalStorage设置相关

    一:退出微信账号后,将会清空全部Cookie和LocalStorage。

     

    二:页面效果信赖Cookie,或有涉及到Cookie的相关逻辑 

    扭转:WKWebview内部完成转移,会潜移默化当下页面Cookie相关的逻辑,譬如跨域存取Cookie和页面的财富或图片存款和储蓄服务器正视校验Cookie来回到数据等情形。

    主题材料求证:在拜访贰个页面A时,要是页面A引用了另一个页面B的财富(页面A和B为分裂的域名),那时页面B就感到是第三方页面。若在页面B中装置Cookie,就能命中WKWebview下阻止第三方跨域设置Cookie的安全攻略,导致难点现身。

    适配提出:

    在WKWebview中是私下认可阻止跨域的第三方设置Cookie。全体通过Cookie传递的消息,可经过职业后台存款和储蓄需求传递的新闻,然后给页面一个存款和储蓄新闻相对应的access_token加密码,然后通过Url中进入自身职业的access_token实行页面间新闻传送。

    一经页面包车型地铁财富或图片存储的服务器依赖校验Cookie来回到数据的处境,在切换来WKWebview后,在微信内长按保存,恐怕点击预览大图时,将不会完好的带上所设置的Cookie,会促成图片保存退步或预览失利。除了此种意况,开拓者不用忧郁其它景况下Cookie丢失的标题,全部伏乞都会带上完整的Cookie。

     

    页面录像小窗播放

    转换:iOS微信6.5.3会同之后的版本中,Webview默许帮助小窗播放。 

    开垦者需求非常注意小窗播放须求前端同期适配iOS10和iOS10以下的低版本 

    适配提出:须要完全根据以下代码设置video标签才可同不常候相配区别的iOS版本

    <video webkit-playsinline playsinline> </video>

     

    WKWebview页面行为与Safari完全一致,会促成页面正视UIWebview页面行为的逻辑失效或特别:(可依靠专门的学业自己逻辑,实现测试页面后分别在Safari和微信WKWebview中证实)

    一:Safari或微信WKWebview中 页面A跳转到页面B再回来页面A后不会另行实施Script和Ajax(也不会触发页面reload)。 

    二:Safari或微信WKWebview中,在页面弹出输入键盘后,会接触jQuery的resize事件,而在UIWebView下不会。 

    三:Safari或微信WKWebview中, window unload 事件在只有刷新能力接触,退出页面只怕跳转到其余页面都爱莫能助接触。 

    四:Safari或微信WKWebview中,极少数情况下一些特殊达成的页面点击事件会失灵。

    要是有关系恐怕碰着以上难点,以包容Safari行为为准。

    wkWebView.scrollView.bounces = NO;
    

    4.从js调用swift

    前方的3有个别都相比较便于,跟WKWebview也差不离。从JS到swift的调用要复杂的多了。
    率先在早先化的时候,要丰盛一句:

            webView!.frameLoadDelegate=self;
    

    相应的,要在类证明的职位加上二个延续:WebFrameLoadDelegate,随后投入代码:

        //为js对象声明一个接口
        func webView(_ webView: WebView!, didClearWindowObject windowObject: WebScriptObject!, for frame: WebFrame!) {
            self.webView.windowScriptObject.setValue(self, forKey: "swiftHost")
        }
        //这个是基本框架,声明了本类中有两个函数会开放给js对象,并供其调用
        //这里示例了两个,一个是callFromJS1,另一个是quit
        //注意swift中的函数名跟js中的函数名可以不一样,
        //#selector中指明的是swift中声明的函数名,因为selector是object-c中的机制,
        //所以后面在声明真正函数的时候,前面必须加@objc的标志
        //在后面return "xxx"的部分,返回的字符串js中会使用的名字,
        //本例中,swift中函数名跟js中函数名使用了相同的名字,我认为这是好习惯
        override class func webScriptName(for aSelector: Selector) -> String?
        {
            //NSLog("%@",aSelector.description)
            if aSelector == #selector(callFromJS1)
            {
                return "callFromJS1"
            }
            else
            if aSelector == #selector(quit)
            {
                return "quit"
            }
            else
            {
                return nil
            }
        }
        //这个函数顾名思义,应当是不允许在js中调用的,对所有的来值都返回false表示全部允许调用
        override class func isSelectorExcluded(fromWebScript aSelector: Selector) -> Bool
        {
            //NSLog("%@",aSelector.description)
            return false
        }
        //具体的函数
        @objc
        func callFromJS1(message:String)
        {
            NSLog(message)
        }
        @objc
        func quit()
        {
            NSLog("call for quit")
            NSApp.terminate(self);
        }
    

    前八个函数是大旨的框架,在那之中第一个麻烦一些,随后实际上专门的学业的函数未有怎么特别。
    随着来探视js的有的:

        <a href='javascript:testCallSwift();'>testCallSwift</a><p>
        <a href='javascript:needQuit();'>Quit</a><p>
        <script>
            function testCallSwift(){
                //注意调用方式,window是js的对象
                //swiftHost是swift的接口
                //其后则是声明的swift函数
                window.swiftHost.callFromJS1("hello swift");
            }
            function needQuit(){
                window.swiftHost.quit();
            }
        </script>
    

    在网页中,只必要像调用js方法一致,实行调用就足以
    <div id='b'><a onclick="window.demo.clickOnAndroid()">b.c</a></div>

    2.移动端展示web方案

    --- 2.1 Safari--- 2.2 SFSafariViewController--- 2.3 UIWebView,回看在信用合作社会群工程中的使用--- 2.3 UIWebView 接口表达

    任何难题

    一:页面自定义重载标准方法也许函数时,需求确认保障不会与微信注入Webview中的JSBridge相关方法争论,不然会促成页面在微信中的行为丰富。

    二:猛烈建议不要在不能保险页面缓存计谋和逻辑与服务器逻辑完全保持一致的动静下冒然设置html页面文件(除了html类型的页面,页面引用的其余能源或脚本依据本身工作合理设置就可以)相关的Cache-Control属性。 

    卓越案例: 

    一旦第三遍访问页面A.html 服务器302跳转到A1.html?uid=111装置Cache-Control: max-age=60,此A1.html的uid参数是服务器设置的111(此时A1.html已经被客户端缓存)。 第三遍访问页面A.html ,服务器同样302跳转到A1.html?uid=222,可是此时的A1.html页面包车型地铁uid参数是222, 客户端带参数完整链接询问服务器缓存是不是可用, 服务器重返缓存可用304,不过客户端缓存的A1.html完整链接带的uid参数是111,所以地方找不到数量,此时加载页面就能够战败。

    3、WKWebview被js调用

    5.截获webview每一次访问

    跟上边类似,要再增加三个代理:

    //初始化的时候增加:
            webView!.policyDelegate=self;
    

    与此同有的时候候评释类的时候多叁个继承:WebPolicyDelegate。随后代码中得以兑现叁个接口:

        func webView(_ webView: WebView!,
                     decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!,
                     request: URLRequest!,
                     frame: WebFrame!,
                     decisionListener listener: WebPolicyDecisionListener!) {
            NSLog("nav to %@",request.url!.absoluteString)  //这里是将要转向的网址
            listener.use()  //允许访问这个网址
            //listener.ignore()   //不允许访问这个网址则调用这个
        }
    

    也可能有个别程序中为了简化从js调用swift的专门的学业量,会用链接的办法,在链接地址中盛传一些指令,就足以用这些函数截获网站并且管理,被拍卖的网站常常选取listener.ignore()来禁止本次浏览器转向,免得影响当下页面。

    3. Java代码调用js并传参 率先须求带参数的js函数,如function test(str),然后只需在调用js时传出参数就可以,如下所示:
    mWebView.loadUrl("javascript:test('aa')");

    3.WKKit& WKWebView

    --- 3.1WKKit框架介绍,WKWebView API介绍--- 3.2OC什么样给JS注入对象及JS怎么着给IOS发送数据--- 3.3JS调用alert、confirm、prompt时,不行使JS原生提醒,而是接纳iOS原生来完成--- 3.4怎么着监听web内容加载进度、是还是不是加载成功--- 3.5什么管理去跨域难点--- 3.6JS和OC的互动调用--- 3.7WKWebview API难题

    window.webkit.messageHandlers.<对象名>.postMessage(body:<数据>)//body中可以直接放js对象,也可以省略body
    
    - userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ NSLog(@"JS 调用了 %@ 方法,传回参数 %@",message.name,message.body); NSMutableDictionary *dic=[message.body objectForKey:@"body"];}
    

    6.响应js中的警告窗

    万般的webview都以不允许js中的alert警告窗的,一方面是为了应用程序全体的作用;另一方面,webview作为叁个空间,自个儿从未UI的调控权,所以类似的干活,是要有应用程序本身实现警告框窗口的。达成警告窗依旧要给类扩充一个合一WebUIDelegate,并在早先化中追加:

            webView!.uiDelegate=self;
    
    //随后可以实现一个接口:
        func webView(_ sender: WebView!,
                     runJavaScriptAlertPanelWithMessage message: String!,
                     initiatedBy frame: WebFrame!){
            NSLog("msg of alert: %@",message)
        }
    

    假如不满意于只是获得警示新闻,要和煦在这一个函数中央银行使cocoa的警戒窗来显示相关的音信。

    4.Js中调用java函数并传参 先是同样须要带参数的函数情势,但需注意此处的参数需求final类型,即得到以往不可修改,假若须求修改当中的值,能够先安装中间变量,然后开始展览更换。如下所示:

    1.背景

    自iOS问世以来,iOS 和web总是亲切。究竟,当iOS诞生的时候,网址已经有15年的野史了(第二个网址的始建乃至能够追溯到一九九三年,而iOS在二〇〇七年才面世,而这时候还未曾AppStore,没有利用分发市镇)Motorola出现的时候就已经有多数的web内容了,那样iOS必须提供一种方法来凸显web内容。----翻译一人苹果程序猿的一段话

    4、WKWebview调用js

    7.其它

    还是能够实现从js中走访swift中的变量作用。使用isKeyExcludedFromWebScriptwebScriptNameForKey函数,笔者用得少,要是须要,参谋上边定义函数的不二等秘书技,查一查官方文书档案自身来尝试吧。

    复制代码 代码如下:

    2.移动端展现web方案

    在iOS 9中,我们有例外的渲染网页内容的选用,根据实际须要,开垦职员能够评估不相同的抉择,选拔三个相符他们越来越好。让大家看看多个开荒职员可以应用的两样的缓和方案。

    让我们看看近些日子在移动端都有如何方案:

    • Safari
    • SFSafariViewController
    • UIWebView
    • WKWebview

    对于前二种大家都已了然依旧调整,大家先简单来讲爱他美下,大家的主导照旧WKWebview上。

    NSData *data=[NSJSONSerialization dataWithJSONObject:self->object options:NSJSONWritingPrettyPrinted error:nil];NSString *dataJson=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSString *dataFunc=[NSString stringWithFormat:@"generalChart",dataJson,(unsigned long)self->chartType]; [self evaluateJavaScript:dataFunc completionHandler:^(id _Nullable param, NSError * _Nullable error) { }];
    

    仿效资料:

    Swift & JavaScript integration

    mWebView.addJavascriptInterface(new Object() {
                public void clickOnAndroid(final int i) {
                    mHandler.post(new Runnable() {
                        public void run() {
                                    int j = i;
                                    j ;
    Toast.makeText(Test.this, "测试调用java" String.valueOf(j), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }, "demo");

    2.1Safari

    咱俩平日用

     NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"]; [[UIApplication sharedApplication] openURL:url];
    

    这种简单的情势用苹果自带的safari浏览器展开三个网页,从iOS9开头从三个app展开另一个app就像内嵌app同样,能够回去原本的app. 就算那是一个纤维的方案,可是对于跳转到其余app,大家依旧某些情愿的,因为,大家只想让用户停留在我们的app里。

    5、wkwebview手势再次来到抖屏难题:webview侧滑重返后会接着触发html页面增添的transition动画导致

    然后在html页面中,利用如下代码<div id='b'><a onclick="window.demo.clickOnAndroid(2)">b.c</a></div>,
    就可以兑现调用

    2.2SFSafariViewController

    大家只可以说safari确实很强劲,在iOS9,苹果公司给大家提供了叁个SafariServices.framework ,那一个框架不会细小略,就多少个文件1.SFSafariViewController2.SSReadingList(用户safari阅读列表)3.SFContentBlockerState(safari内容拦击)不用明白

    此地只是轻松询问下SFSafariViewController,这么些调控器的API,很轻便。用SFSafariViewController 这种方式能够加载web内容,而且是内置在大家app里的浏览器,然则那一个调节器有个沉重的宿疾便是不可能自定义,苹果集团并未开放出过多API,有一对民用的API可以拿走进展自定义,但是大家不可能动用,略显窘迫,我想就此苹果集团不开放大多api的说辞,应该入眼依然以原生app和safari为主流的案由吧。

     [wkWebView setAllowsBackForwardNavigationGestures:true];//设置手势返回
    

    您只怕感兴趣的稿子:

    • android WebView加载html5介绍
    • Android中贯彻Webview顶上部分带进度条的主意
    • android中webview控件和javascript交互实例
    • Android WebView使用格局详解 附js交互调用方法
    • android webview中选用Java调用JavaScript方法并拿走再次来到值
    • Android中Webview展开网页的还要发送HTTP头音信方法
    • 在Android系统中运用WebViewClient管理跳转U中华VL的章程
    • Android开垦之WebView组件的选用分析
    • Android中 webView调用JS出错的化解办法
    • Android混合开拓教程之WebView的选取方式计算
    2.3UIWebView

    废话非常的少说,大家把关键放在最终WkWebview上,再认知WKWebview在此以前,我们有至关重要再轻松回想下UIwebView的施用,以及大家工程里对UIwebview的使用.UIWebview是UIKit框架里的三个视图类, 继承UIView, 整个接口文件也唯有100行,里面有七个scrollview的性格,那些都以大家大致的认知。大家感兴趣能够明白下UIwebView的其中贯彻,前面稍微提一下。

    1.企业对UIWebview的简练利用1.1用webView打电话代码如下

     NSString *phoneNum = nil; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0){ phoneNum = [NSString stringWithFormat:@"telprompt://%@",self.phoneNumber]; } else { phoneNum = [NSString stringWithFormat:@"tel://%@",self.phoneNumber];// 电话号码 } if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]]; } else { UIWebView *callPhoneWebVw = [[UIWebView alloc] initWithFrame:CGRectZero]; self.callwebView = callPhoneWebVw; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:phoneNum]]; [_callwebView loadRequest:request]; }
    

    1.2 封装了 PZLWJSBridgeView ,控件承袭UIWebview在家居和学识详细情形模块,都有用到那么些类1.3LLLwebviewcontroller大家都明白,我们最多的是选择那一个类,加载wap页面,大家在此地大致看下这么些调整器是怎么利用的。其实选拔也是蛮简单的,具体步骤如下:1.3.1开立UIwebview1.3.2创立假的进程条,之所以是假的,是因为webview不辅助加载进程1.3.3然后便是一对享用专门的工作上的逻辑了(轻巧调用js代码获取js数据)1.3.4 每一回央求的时候有增添cookie的操作,然后dealloc的时候删除 cookie(UIwebview并不协助cookie操作)1.3.5 加载URAV4L过滤,PZLWUPRADOLRequestFilter: NSUQX56LProtocol,咱供销合作社对于这几个三番五次自NSULX570LProtocol的文本也打成了静态库,感兴趣的同班可以去github上找一下, github有落到实处德姆o。但是这一个U奇骏L过滤,在WKWebView上不帮助。我们大约学习一下这些在我们商家封装成静态库的贯彻进程吧

    我们用UIWebview无非正是八个代理和调用javascript代码,而且只是获得html的原委。像这么 :

    [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('soufunclient').innerHTML"];
    

    如上所述,UIwebview的应用异常的粗略,这里对UIWebview头文件做了印证

    // Copyright  2007-2015 Apple Inc. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIView.h>#import <UIKit/UIKitDefines.h>#import <UIKit/UIDataDetectors.h>#import <UIKit/UIScrollView.h>NS_ASSUME_NONNULL_BEGINtypedef NS_ENUM(NSInteger, UIWebViewNavigationType) { UIWebViewNavigationTypeLinkClicked,//用户触发了一个链接 UIWebViewNavigationTypeFormSubmitted,//用户提交了一个表单 UIWebViewNavigationTypeBackForward,//用户触击前进前进或返回按钮 UIWebViewNavigationTypeReload,//用户触击重新加载的按钮 UIWebViewNavigationTypeFormResubmitted,//用户重复提交表单 UIWebViewNavigationTypeOther//发生了其他行为} __TVOS_PROHIBITED;//2. 加载内容关于分页显示几种不同类型typedef NS_ENUM(NSInteger, UIWebPaginationMode) { UIWebPaginationModeUnpaginated, UIWebPaginationModeLeftToRight, UIWebPaginationModeTopToBottom, UIWebPaginationModeBottomToTop, UIWebPaginationModeRightToLeft} __TVOS_PROHIBITED;typedef NS_ENUM(NSInteger, UIWebPaginationBreakingMode) { UIWebPaginationBreakingModePage,//默认设置是这个属性,CSS属性以页样式。 UIWebPaginationBreakingModeColumn//当UIWebPaginationBreakingMode设置这个属性的时候,这个页面内容CSS属性以column-break 代替page-breaking样式。} __TVOS_PROHIBITED;@class UIWebViewInternal;@protocol UIWebViewDelegate;NS_CLASS_AVAILABLE_IOS __TVOS_PROHIBITED @interface UIWebView : UIView <NSCoding, UIScrollViewDelegate> @property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;@property (nonatomic, readonly, strong) UIScrollView *scrollView NS_AVAILABLE_IOS;- loadRequest:(NSURLRequest *)request;- loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;- loadData:data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:baseURL;@property (nullable, nonatomic, readonly, strong) NSURLRequest *request;- reload;- stopLoading;- goBack;- goForward;@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;@property (nonatomic, readonly, getter=isLoading) BOOL loading;- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;//是否让内容伸缩至适应屏幕当前尺寸@property (nonatomic) BOOL scalesPageToFit;//这个属性如果设置为YES,当进入到页面视图可以自动检测电话号码,让用户可以单机号码进行拨打,不过现已弃用。@property (nonatomic) BOOL detectsPhoneNumbers NS_DEPRECATED_IOS;//这个属性可以设定使电话号码,网址,电子邮件和符合格式的日期等文字变为连接文字。@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS;//这个属性决定了页面用内嵌HTML5播放视频还是用本地的全屏控制。为了内嵌视频播放,不仅仅需要在这个页面上设置这个属性,还需要在HTML的viedeo元素必须包含webkit-playsinline属性。默认iPhone为NO,iPad为YES。@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS; // iPhone Safari defaults to NO. iPad Safari defaults to YES//这个属性决定了HTML5视频可以自动播放还是需要用户启动播放。iPhone和iPad默认都是YES。@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS; // iPhone and iPad Safari both default to YES//这个属性决定了从这个页面是否可以Air Play。iPhone和iPad上都是默认YES。@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS; // iPhone and iPad Safari both default to YES//这个值决定了网页内容的渲染是否在把内容全部加到内存中再去处理。如果设置为YES,只有网页内容加载到内存里了才会去渲染。默认为NO@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS; // iPhone and iPad Safari both default to NO//这个属性如果设置为YES,用户必须明确的点击页面上的元素或者相关联的输入页面来显示键盘。如果设置为NO,一个元素的焦点事件就会导致输入视图的显示和自动关联这个元素。@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS; // default is YES//设置页面分页模型选择。@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS;//这个属性决定了CSS属性是采用column-break 还是page-breaking样式。@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS;//分页的长度@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS;//分页之间间距@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS;//分页的个数@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS;//是否允许画中画播放The default value is YES on devices that support Picture in Picture  mode and NO on all other devices.@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback NS_AVAILABLE_IOS;//3DTouch的预览功能,默认为NO@property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE_IOS; // default is NO@end__TVOS_PROHIBITED @protocol UIWebViewDelegate <NSObject>@optional- webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;- webViewDidStartLoad:(UIWebView *)webView;- webViewDidFinishLoad:(UIWebView *)webView;- webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;@endNS_ASSUME_NONNULL_END
    

    未来小编告诉您, 终于进行大家要讲的核心了,不佳意思,未来才起来,然则也会连忙完工的。

    6、wkwebview不能跳转App Store

    3 WKKit && WKWebview
    - webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler{ WKNavigationActionPolicy policy =WKNavigationActionPolicyAllow; if([[navigationAction.request.URL host] isEqualToString:@"itunes.apple.com"] &&[[UIApplication sharedApplication] openURL:navigationAction.request.URL]) { policy =WKNavigationActionPolicyCancel; } decisionHandler;}
    
    3.1WKKit框架介绍,WKWebView API介绍

    WKWebview在WKKit这一个框架里, 苹果将UIWebViewDelegate和UIWebView重构成了十七个类与3个体协会议官方链接

    WebKit provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited. WebKit greatly simplifies the complicated process of loading webpages—that is, asynchronously requesting web content from an HTTP server where the response may arrive incrementally, in random order, or partially due to network errors. WebKit also simplifies the process of displaying that content which can contain various MIME types, and compound frame elements each with their own set of scroll bars.

    在Overview的时候,苹果官方文书档案有诸如此类的一段描述。并且还有贰个唤起

    Concurrency NoteThe WebKit framework is not thread-safe. If you call functions or methods in this framework, you must do so exclusively on the main program thread.

    不是线程安全的。同样的WebKit框架在MAC app和 iOS 应用程式里是不相同的, 我们能够见见在macAPP里,那么些框架是相当的大的, 里面还包蕴了子框架, 而且这一个框架暴光的头文件也好多,有CSS,DOM等操作的API.

    说了这么多,大家稍等一会就只来探视iOS上webkit框架,如若大家刚兴趣能够学学也许精晓一下MAC上的webkit框架

    WWDC2014-206session:The modern Webkit APi1.Same on iOS and OS X2.Modern3.Streamlined4.Multi-process architecture

    新葡亰496net 1Multi-process architecture

    咱俩先是了解下WKWebView的部分优势:1WKWebview在性质、坚固性上和UIwebview比较2WKWebView更加多的支撑HTML5的特征3WKWebView更加快,占用内部存款和储蓄器恐怕只有UIWebView的三分一 ~ 54%4WKWebView高达60fps的滚动刷新率和丰硕的放置手势(Built-in gestures)5WKWebView具备Safari一样的JavaScript引擎Nitro(JJT多少个经过解释实行优化js代码)(FastJavaScript)6WKWebView增添了加载进度属性7Easy app-webpage communication8Responsive scrolling9更省电量 battery以上音信能够在WWDC二零一五-206节-介绍 WebKit modern API 的时候提到。

    ** po [self.webView recursiveDescription]<UIWebView: 0x14d14130; frame = (0 0; 320 504); layer = <CALayer: 0x12cca690>> | <_UIWebViewScrollView: 0x6c55400; frame = (0 0; 320 504); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x12c7adf0>; layer = <CALayer: 0x10a4f9c0>; contentOffset: {0, 0}; contentSize: {320, 504}> | | <UIWebBrowserView: 0x69fac00; frame = (0 0; 320 504); text = ''; gestureRecognizers = <NSArray: 0x10ac37f0>; layer = <UIWebLayer: 0x12c9f580>> | | | <LegacyTileHostLayer: 0x14d04c30>  | | | | <LegacyTileLayer: 0x10a99700>  | | <UIImageView: 0x14d0ffd0; frame = (3 498.5; 314 2.5); alpha = 0; opaque = NO; autoresize = TM; userInteractionEnabled = NO; layer = <CALayer: 0x14d100b0>> | | <UIImageView: 0x14c4e3a0; frame = (314.5 3; 2.5 498); alpha = 0; opaque = NO; autoresize = LM; userInteractionEnabled = NO; layer = <CALayer: 0x14ceb340>>** po [self.webView recursiveDescription]**<WKWebView: 0x1612c8720; frame = (0 0; 320 504); layer = <CALayer: 0x16127b9b0>> | <WKScrollView: 0x160977600; baseClass = UIWebScrollView; frame = (0 0; 320 504); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x16488d250>; layer = <CALayer: 0x16488a970>; contentOffset: {0, 0}; contentSize: {0, 0}> | | <WKContentView: 0x160a56000; frame = (0 0; 320 504); gestureRecognizers = <NSArray: 0x164887d20>; layer = <CALayer: 0x16127b650>> | | | <UIView: 0x16129d960; frame = (0 0; 320 504); clipsToBounds = YES; layer = <CALayer: 0x1612c3150>> | | | | <UIView: 0x1612c2fe0; frame = (0 0; 320 504); autoresize = W H; layer = <CALayer: 0x16128a9f0>> | | <UIView: 0x164887750; frame = ; opaque = NO; layer = <CALayer: 0x16127a070>> | | <UIImageView: 0x16102fa70; frame = (310 498.5; 7 2.5); alpha = 0; opaque = NO; autoresize = TM; userInteractionEnabled = NO; layer = <CALayer: 0x161227960>> | | <UIImageView: 0x163647e60; frame = (314.5 494; 2.5 7); alpha = 0; opaque = NO; autoresize = LM; userInteractionEnabled = NO; layer = <CALayer: 0x1610ac060>>
    

    新葡亰496net 2UIWebView.png 引用自CocoaChina

    UIWebView属于UIKit,封装了Web基特.framework的WebView.WebView组合管理了WebCore.framework的Page,并提供了各类Clients.Page管理了Main Frame,Main Frame处理了sub Frame(FrameTree)大家看一下po出来的视图层级完全不一致样,能够说两个关系并十分小,WebView承接自WAKView,WAKView类似于NSView,能够做较少的更换使得Mac和iOS共用一套。由UIWebDocumentView对WebView举行操作并吸收接纳回调事件,当数码爆发变化的时候,就可以公告UIWebTiledView重新绘制。UIWebTiledView和WAKWindow那七个类主要担任页面包车型大巴绘图,蕴含布局绘图排版,交互等,WAKWindow还有只怕会做一些用户操作事件的分摊。UIWebBrowserView主要担任: form的电动填充 fixed成分的职分调治JavaScript的手势识别, 键盘弹出时的视图滚动管理,防止遮挡,提供接口让UIWebView获取新闻,为显示PDF时增添页号标签

    • -- 引在cocoachina一篇小说

    不过本身在其实地度量试的时候, 在真机上冒出过接到内部存款和储蓄器警告。下边两张图片比较下加载www.fang.com的wap页的时候,以及点击wap的时候内部存储器变化的图景。

    新葡亰496net 3UIWebView内部存款和储蓄器变化情形新葡亰496net 4WKWebview内部存款和储蓄器变化境况

    从地点三个图纸能够观察,刚开端加载网页的时候内部存款和储蓄器使用是基本上的, 不过当本人和wap页面交互的时候,内部存款和储蓄器变化对于UIWebview来讲是巨大的, 对于WkWebView来讲相对是相当小的。

    Class:

    WKBackForwardList: 此前访问过的 web 页面包车型地铁列表,能够透过后退和进步动作来访问到。WKBackForwardListItem: webview 中后退列表里的某几个网页。WKFrameInfo: 包涵三个网页的布局音信。WKNavigation: 包罗多少个网页的加载进程新闻。WKNavigationAction: 包括可能让网页导航变化的音信,用于推断是不是做出导航变化。WKNavigationResponse: 蕴涵或许让网页导航变化的归来内容音信,用于决断是或不是做出导航变化。WKPreferences: 回顾一个 webview 的忠爱设置。WKProcessPool: 表示二个 web 内容加载池。WKUserContentController: 提供利用 JavaScript post 消息和注射 script 的不二秘诀。WKScriptMessage: 包括网页发出的讯息。WKUserScript: 表示能够被网页接受的用户脚本。WKWebViewConfiguration: 开始化 webview 的安装。WKWindowFeatures: 内定加载新网页时的窗口属性。

    WKUserScript:

    What Can User Scripts Do?Incredibly powerful• Modify the document• Listen for events• Load resources• Communicate back to your application

    Protocal:

    WKNavigationDelegate: 提供了追踪主窗口网页加载进程和判定主窗口和子窗口是不是实行页面加载新页面包车型地铁相干措施。WKScriptMessageHandler: 提供从网页中收音信的回调方法。WKUIDelegate: 提供用原生控件展现网页的法子回调。

    明天让我们跳到Xcode

    /*说明: 1.WKProcessPool@abstract The process pool from which to obtain the view's web content process. @discussion When a web view is initialized, a new web content process will be created for it from the specified pool, or an existing process in that pool will be used. ! A WKProcessPool object represents a pool of web content processes. The process pool associated with a web view is specified by its web view configuration. Each web view is given its own web content process until an implementation-defined process limit is reached; after that, web views with the same process pool end up sharing web content processes. 这个东西好像与cookie有关,一个例子。 2WKUserContentController A WKUserContentController object provides a way for JavaScript to post messages to a web view. The user content controller associated with a web view is specified by its web view configuration. 3 它是用于webview内容交互时选择内容的粒度类型设置。比如说,当使用WKSelectionGranularityDynamic时,而所选择的内容是单个块,这时候granularity可能会是单个字符;当所选择的web内容不限制于某个块时,granularity可能会是单个块。*/#import "LLLWKwebViewViewController.h"//1.第一步导入框架#import <WebKit/WebKit.h>//大家可以看一下,这个Webkit包含了27个文件,我们不能讲的很详细, 只能尽力去说一下@interface LLLWKwebViewViewController ()<WKNavigationDelegate,WKUIDelegate>@property(nonatomic,strong)WKWebView *wkwebview;@end@implementation LLLWKwebViewViewController- viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // WKWebView *wkView = [[WKWebView alloc]initWithFrame:self.view.bounds]; //3.初始化WKPreferences WKPreferences *preference = [[WKPreferences alloc]init]; preference.minimumFontSize = 0; preference.javaScriptEnabled = YES; preference.javaScriptCanOpenWindowsAutomatically=NO; //4初始化WKUserContentController WKUserContentController *wkuserCVC = [[WKUserContentController alloc]init]; // [wkuserCVC addUserScript:nil]; // [wkuserCVC addScriptMessageHandler:<#(nonnull id<WKScriptMessageHandler>)#> name:<#(nonnull NSString *)#>] //5.WKWebsiteDataStore WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore]; dataStore = [WKWebsiteDataStore nonPersistentDataStore];//适合隐私浏览 NSSet *set = [WKWebsiteDataStore allWebsiteDataTypes]; NSArray *arr = [set allObjects]; // [dataStore fetchDataRecordsOfTypes:(nonnull NSSet<NSString *> *) completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull) { // }]; // [dataStore removeDataOfTypes:(nonnull NSSet<NSString *> *) forDataRecords:(nonnull NSArray<WKWebsiteDataRecord *> *) completionHandler:^{ //}]; //6WKWebsiteDataRecord // WKWebsiteDataRecord *dataRecord = [[WKWebsiteDataRecord alloc]init]; // dataRecord.dataTypes //2.初始化设置 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init]; config.processPool = [[WKProcessPool alloc]init]; config.preferences = preference; config.userContentController = wkuserCVC; config.websiteDataStore = dataStore; config.suppressesIncrementalRendering = NO;//ioS9 config.applicationNameForUserAgent = @"USer-agent";//ios9 config.allowsAirPlayForMediaPlayback =YES;//airplay isallowed config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;//ios10 config.allowsInlineMediaPlayback = NO; config.selectionGranularity = WKSelectionGranularityDynamic; config.allowsPictureInPictureMediaPlayback = NO; config.dataDetectorTypes = UIDataDetectorTypePhoneNumber; config.ignoresViewportScaleLimits = NO; WKWebView*wkView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config]; self.wkwebview = wkView; WKBackForwardList *list = wkView.backForwardList; WKBackForwardListItem *backlistItem = list.backItem; WKBackForwardListItem *forwardlistItem = list.forwardItem; WKBackForwardListItem *currentlistItem = list.currentItem; WKBackForwardListItem *nextlistItem = [list itemAtIndex:1]; NSArray *backList = list.backList; NSArray *forwardList = list.forwardList; WKNavigation *navigation = [wkView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.fang.com"]]]; wkView.UIDelegate = self; wkView.navigationDelegate = self; [self.view addSubview:wkView]; }#pragma mark---WKNavigationDelegate/*! @abstract Decides whether to allow or cancel a navigation. @param webView The web view invoking the delegate method. @param navigationAction Descriptive information about the action triggering the navigation request. @param decisionHandler The decision handler to call to allow or cancel the navigation. The argument is one of the constants of the enumerated type WKNavigationActionPolicy. @discussion If you do not implement this method, the web view will load the request or, if appropriate, forward it to another application. *///1.The number 1 called//3.The number 3 called//7.The number 7 called- webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler{ NSLog(@"%s--navigationAction is %@",__FUNCTION__,navigationAction); decisionHandler(WKNavigationActionPolicyAllow);}/*! @abstract Decides whether to allow or cancel a navigation after its response is known. @param webView The web view invoking the delegate method. @param navigationResponse Descriptive information about the navigation response. @param decisionHandler The decision handler to call to allow or cancel the navigation. The argument is one of the constants of the enumerated type WKNavigationResponsePolicy. @discussion If you do not implement this method, the web view will allow the response, if the web view can show it. *///5.The number 5 called- webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(WKNavigationResponsePolicy))decisionHandler{ NSLog(@"%s--navigationAction is %@",__FUNCTION__,navigationResponse); decisionHandler(WKNavigationResponsePolicyAllow); }/*! @abstract Invoked when a main frame navigation starts. @param webView The web view invoking the delegate method. @param navigation The navigation. #########Called when web content begins to load in a web view. *///2.the number 2 called- webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{ NSLog(@"%s--navigation is %@",__FUNCTION__,navigation);}/*! @abstract Invoked when a server redirect is received for the main frame. @param webView The web view invoking the delegate method. @param navigation The navigation. *///4.The number 4 called- webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{ NSLog(@"%s--navigation is %@",__FUNCTION__,navigation);}/*! @abstract Invoked when an error occurs while starting to load data for the main frame. @param webView The web view invoking the delegate method. @param navigation The navigation. @param error The error that occurred. */- webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{ NSLog(@"%s--navigation is %@ and error is %@",__FUNCTION__,navigation,error);}/*! @abstract Invoked when content starts arriving for the main frame. @param webView The web view invoking the delegate method. @param navigation The navigation. ################Called when the web view begins to receive web content. *///6.The number 6 called- webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{ NSLog(@"%s--navigation is %@",__FUNCTION__,navigation);}/*! @abstract Invoked when a main frame navigation completes. @param webView The web view invoking the delegate method. @param navigation The navigation. */- webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{ NSLog(@"%s--navigation is %@",__FUNCTION__,navigation);}/*! @abstract Invoked when an error occurs during a committed main frame navigation. @param webView The web view invoking the delegate method. @param navigation The navigation. @param error The error that occurred. */- webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{ NSLog(@"%s--navigation is %@",__FUNCTION__,navigation);}/*! @abstract Invoked when the web view needs to respond to an authentication challenge. @param webView The web view that received the authentication challenge. @param challenge The authentication challenge. @param completionHandler The completion handler you must invoke to respond to the challenge. The disposition argument is one of the constants of the enumerated type NSURLSessionAuthChallengeDisposition. When disposition is NSURLSessionAuthChallengeUseCredential, the credential argument is the credential to use, or nil to indicate continuing without a credential. @discussion If you do not implement this method, the web view will respond to the authentication challenge with the NSURLSessionAuthChallengeRejectProtectionSpace disposition. */- webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{ NSLog(@"%s--challenge is %@",__FUNCTION__,challenge); completionHandler(NSURLSessionAuthChallengeUseCredential,nil);}/*! @abstract Invoked when the web view's web content process is terminated. @param webView The web view whose underlying web content process was terminated. */- webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx, ios{ NSLog(@"%s-",__FUNCTION__);}- didReceiveMemoryWarning { [super didReceiveMemoryWarning];}#pragma mark---WKUIDelegate/*! @abstract Creates a new web view. @param webView The web view invoking the delegate method. @param configuration The configuration to use when creating the new web view. @param navigationAction The navigation action causing the new web view to be created. @param windowFeatures Window features requested by the webpage. @result A new web view or nil. @discussion The web view returned must be created with the specified configuration. WebKit will load the request in the returned web view. If you do not implement this method, the web view will cancel the navigation. */- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{ NSLog(@"%s--configuration is %@ n and navigationAction is %@n and windowFeatures is %@",__FUNCTION__,configuration,navigationAction,windowFeatures); return webView;}/*! @abstract Notifies your app that the DOM window object's close() method completed successfully. @param webView The web view invoking the delegate method. @discussion Your app should remove the web view from the view hierarchy and update the UI as needed, such as by closing the containing browser tab or window. */- webViewDidClose:(WKWebView *)webView API_AVAILABLE(macosx, ios{ NSLog(@"%s-",__FUNCTION__);}/*! @abstract Displays a JavaScript alert panel. @param webView The web view invoking the delegate method. @param message The message to display. @param frame Information about the frame whose JavaScript initiated this call. @param completionHandler The completion handler to call after the alert panel has been dismissed. @discussion For user security, your app should call attention to the fact that a specific website controls the content in this panel. A simple forumla for identifying the controlling website is frame.request.URL.host. The panel should have a single OK button. If you do not implement this method, the web view will behave as if the user selected the OK button. */- webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:completionHandler{ NSLog(@"%s and message is %@ and frame is %@",__FUNCTION__,message,frame);}/*! @abstract Displays a JavaScript confirm panel. @param webView The web view invoking the delegate method. @param message The message to display. @param frame Information about the frame whose JavaScript initiated this call. @param completionHandler The completion handler to call after the confirm panel has been dismissed. Pass YES if the user chose OK, NO if the user chose Cancel. @discussion For user security, your app should call attention to the fact that a specific website controls the content in this panel. A simple forumla for identifying the controlling website is frame.request.URL.host. The panel should have two buttons, such as OK and Cancel. If you do not implement this method, the web view will behave as if the user selected the Cancel button. */- webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(BOOL result))completionHandler{ NSLog(@"%s and message is %@ and frame is %@",__FUNCTION__,message,frame);}/*! @abstract Displays a JavaScript text input panel. @param webView The web view invoking the delegate method. @param message The message to display. @param defaultText The initial text to display in the text entry field. @param frame Information about the frame whose JavaScript initiated this call. @param completionHandler The completion handler to call after the text input panel has been dismissed. Pass the entered text if the user chose OK, otherwise nil. @discussion For user security, your app should call attention to the fact that a specific website controls the content in this panel. A simple forumla for identifying the controlling website is frame.request.URL.host. The panel should have two buttons, such as OK and Cancel, and a field in which to enter text. If you do not implement this method, the web view will behave as if the user selected the Cancel button. */- webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(NSString * _Nullable result))completionHandler{ NSLog(@"%s and prompt is %@ and defaulttext is %@ and frame is %@",__FUNCTION__,prompt,defaultText,frame);}/*! @abstract Allows your app to determine whether or not the given element should show a preview. @param webView The web view invoking the delegate method. @param elementInfo The elementInfo for the element the user has started touching. @discussion To disable previews entirely for the given element, return NO. Returning NO will prevent webView:previewingViewControllerForElement:defaultActions: and webView:commitPreviewingViewController: from being invoked. This method will only be invoked for elements that have default preview in WebKit, which is limited to links. In the future, it could be invoked for additional elements. */- webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo API_AVAILABLE){ NSLog(@"%s-%@",__FUNCTION__, elementInfo); return YES;}/*! @abstract Allows your app to provide a custom view controller to show when the given element is peeked. @param webView The web view invoking the delegate method. @param elementInfo The elementInfo for the element the user is peeking. @param defaultActions An array of the actions that WebKit would use as previewActionItems for this element by default. These actions would be used if allowsLinkPreview is YES but these delegate methods have not been implemented, or if this delegate method returns nil. @discussion Returning a view controller will result in that view controller being displayed as a peek preview. To use the defaultActions, your app is responsible for returning whichever of those actions it wants in your view controller's implementation of -previewActionItems. Returning nil will result in WebKit's default preview behavior. webView:commitPreviewingViewController: will only be invoked if a non-nil view controller was returned. */- (nullable UIViewController *)webView:(WKWebView *)webView previewingViewControllerForElement:(WKPreviewElementInfo *)elementInfo defaultActions:(NSArray<id <WKPreviewActionItem>> *)previewActions API_AVAILABLE){ NSLog(@"%s",__FUNCTION__); return nil;}/*! @abstract Allows your app to pop to the view controller it created. @param webView The web view invoking the delegate method. @param previewingViewController The view controller that is being popped. */- webView:(WKWebView *)webView commitPreviewingViewController:(UIViewController *)previewingViewController API_AVAILABLE){ NSLog(@"%s",__FUNCTION__);}@end
    

    1.通过直接流入js代码, 我们得以做过多作业,上面已经关系1 .1Modify the document1.2 Listen for events1.3 Load resources1.4Communicate back to your application

     WKUserContentController *wkuserCVC = [[WKUserContentController alloc]init]; WKUserScript *script = [[WKUserScript alloc]initWithSource:@"js code" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]; [wkuserCVC addUserScript:script];
    

    2.WKUserContentController是用以给JS注入对象的,注入对象后,JS端就能够利用:

    window.webkit.messageHandlers.<name>.postMessage(<messageBody>) 
    

    来调用发送数据给iOS端,举例:

    window.webkit.messageHandlers.AppModel.postMessage({body: '传数据'});
    

    OC则是流入对象是,设置了二个代理

    #pragma mark @protocol WKScriptMessageHandler <NSObject>/*! @abstract Invoked when a script message is received from a webpage. @param userContentController The user content controller invoking the delegate method. @param message The script message received. */- userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ NSLog(@"%s and messgae is %@nnn",__FUNCTION__,message);}
    

    今日大家因而上述代码的求学,基本概略精晓了WKwebview 的API的施用,那之中山高校概共计有27七个类, 还可能有大多的协商。常用的大家第一通晓了, 然后有的时候用的豪门也得以多钻研一下。

    OC代码咋是吸纳代理现在,呈现原生的控件,代码如下,这里大家

    - webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(NSString * _Nullable result))completionHandler{ NSLog(@"%snnn prompt:%@ defaultText:%@ frame:%@",__FUNCTION__,prompt,defaultText,frame); UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"prompt" message:[NSString stringWithFormat:@"prompt:%@ndefaultText:%@nframe:%@",prompt,defaultText,frame] preferredStyle:UIAlertControllerStyleAlert]; [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.textColor = [UIColor blueColor]; }]; [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler([[alertVc.textFields lastObject] text]); }]]; [self presentViewController:alertVc animated:YES completion:^{ }];}
    

    WKWebView 有贰天性能estimatedProgress,这一个便是加载进程。大家运用KVO监听那么些属性值的变动,就足以显得加载进程了。

     [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    #pragma mark - WKNavigationDelegate- webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler { NSString *hostname = navigationAction.request.URL.host.lowercaseString; if (navigationAction.navigationType == WKNavigationTypeLinkActivated && ![hostname containsString:@".baidu.com"]) {// 对于跨域,需要手动跳转 [[UIApplication sharedApplication] openURL:navigationAction.request.URL]; // 不允许web内跳转 decisionHandler(WKNavigationActionPolicyCancel); } else { self.progressView.alpha = 1.0; decisionHandler(WKNavigationActionPolicyAllow); } NSLog(@"%s", __FUNCTION__);}
    

    因为先天WKWebView会忽视暗中同意的网络存款和储蓄, NSU凯雷德LCache, NSHTTPCookieStorage, NSCredentialStorage。 前段时间是这样的,WKWebView有和好的进程,同样也会有和好的仓库储存空间用来存储cookie和cache, 别的的互连网类如NSUTucsonLConnection是不可能访问到的。 同偶然间WKWebView发起的财富央求也是不通过NSU锐界LProtocol的,导致不能自定义央浼不可不可以认的,WKWebView确实要好用,APP内的展现也很好,但玩弄的地点也是蛮多的。

     WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];// dataStore = [WKWebsiteDataStore nonPersistentDataStore];//适合隐私浏览 NSSet *set = [WKWebsiteDataStore allWebsiteDataTypes]; NSArray *arr = [set allObjects]; // [dataStore fetchDataRecordsOfTypes:(nonnull NSSet<NSString *> *) completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull) { // }]; [dataStore removeDataOfTypes:set forDataRecords:arr completionHandler:^{ }]; [dataStore removeDataOfTypes:set modifiedSince:[NSDate dateWithTimeIntervalSinceNow:-100] completionHandler:^{ }]; 
    

    先是种:有为数十分的多的app直接行使在webview的代办中通过拦截的法门与native举行互动,平日是经过拦截url scheme判定是不是是我们需求拦截管理的url及其所对应的要管理的功效是怎么。任意版本都帮助。第二种:iOS7后头出了JavaScriptCore.framework用于与JS交互,可是不援救iOS6,对于还索要援救iOS6的app,就不可能设想那几个了。若须求通晓,看末了的推荐阅读。第两种:WebViewJavascriptBridge开源库使用,本质上,它也是经过webview的代理拦截scheme,然后注入相应的JS。第几种:react-native

    对于第一种,其实在上文的授课中可能穿插了, 这里差非常的少总括下:1.OC调用JS代码

    UIWebview:[webView stringByEvaluatingJavaScriptFromString:@"helloWithName"];WKWebview: [self.webView evaluateJavaScript:@"document.getElementById('soufunclient').innerHTML" completionHandler:^(id _Nullable string, NSError * _Nullable error) { shareContent = [NSString stringWithFormat:@"%@",string]; }];//在这里说明一下,上面的方法是同步的,而WKwebView的方法是异步的。
    

    2JS调用OC代码UIWebView:

    //具体让js文告native举市场价格势调用,大家得以让js爆发三个异军突起的诉求。可以让Native代码能够阻止到,而且不然用户发掘。业界一般的兑现方案是在网页中加载多少个掩蔽的iframe来贯彻该意义。通过将iframe的src钦赐为多个例外的U揽胜极光L,完结在- webView:(UIWebView )webView shouldStartLoadWithRequest:(NSUPRADOLRequest )request navigationType:(UIWebViewNavigationType)navigationType;方案中进行阻挠管理。对应的js调用代码如下:

     function loadURL { var iFrame; iFrame = document.createElement; iFrame.setAttribute("src", url); iFrame.setAttribute("style", "display:none;"); iFrame.setAttribute("height", "0px"); iFrame.setAttribute("width", "0px"); iFrame.setAttribute("frameborder", "0"); document.body.appendChild; // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉 iFrame.parentNode.removeChild; iFrame = null; }
    

    WKWebView:对于WkwebView大家地点3.2 OC怎么着给JS注入对象及JS如何给IOS发送数据已经讲到了。

    当然这里的下结论是最简便的。我们有未有想过,我们怎么手艺通晓js里的哪些措施OC能够调用,同样OC里什么模块,JS也晓得能够调用呢,React Native 是FaceBook开源的, 我们能够活动百度学习,很牛啊。

    对此第三种:javascriptcore.framework大家事先分享JS帕特ch的时候简单讲过,这里我们再从这篇小说轻便讲一下js和OC是通过那个框架互相调用的办法。

    对于第两种WebViewJavascriptBridge,第三方框架,挺闻明的, 具体的贯彻是透过webview拦截的措施。笔者从不仔细的去看,就不讲了,感兴趣的同窗能够探究。

    对此React Native ,那些达成原理很牛掰,大家自身能够搜一下法则看看,那一个利用JSX编写,就js和html……,那一个东西一贯不学过,笔者也非常少说了,临时间依然必要上学一下的,有些商家曾经应用生产了,搞定了想热修复一样的成效。

    当今JS和OC交互大家大致就讲完了。1UIWebview拦截 ,推行js代码2WkWebview注入js对象,OC回调,当然小编个人感到在服务器发送响应头也是足以做阻止的,和UIwebview一样,但是未有察觉英特网有这么说的。3便是WebViewJavascriptBridge第三方拦截框架,根本上是对上边包车型客车卷入4ReacNative 那些就不说了,基本就是用的 JSBridge ,运转时

    末段我们来学学这两篇小说1. 文章是贰个印度人收拾的,是一篇非常不错的篇章。

    wkwebview无法跳转集团安装

    进阶

    - webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler{ NSString *strRequest = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; if ([strRequest containsString:@"itms-services"]) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]]; } decisionHandler;}
    
    1.利用safari对webview实行调治将养

    感兴趣的校友也足以学学一下

    7、wkwebview监听事件

    2.WebView加载HTML图片大小自适应与篇章自动换行

    编制程序,Ajax,jquery框架,当然假令你对前者感兴趣能够修行一下

    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];[webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];// 进度条[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];// 只要观察的对象属性有新值就会调用- observeValueForKeyPath:(NSString *)keyPath ofObject:object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:context{ NSLog(@"%d, %d", self.webView.canGoForward, self.webView.canGoBack);}
    
    3.WKWebViewでJavaScript(Alert,Confirm,Prompt)の処理

    8、wkwebview关于魅族X页面适配,全屏突显,开掘最上端出现20px的空白增加运行图

    4WBWebViewConsole

    新葡亰496net 5增加X启动图

    5 iOS10ATS问题

    AppDelegate的didFinishLaunchingWithOptions方法中增多

    6Cookie问题
     if (@available(iOS 11.0, *)) { [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever]; }
    

    webview添加

    if (@available(iOS 11.0, *)) { wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;}else { self.edgesForExtendedLayout = UIRectEdgeNone;}
    

    9、wkwebview不可能加载沙盒中Doc下目录中html,供给放在tem从mainBundle拷贝文件夹到tem

     NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"dist" ofType:@""]; NSString *path = NSTemporaryDirectory(); NSString *cacheStr=[NSString stringWithFormat:@"%@/dist",path]; NSFileManager * defaultManager = [NSFileManager defaultManager]; NSError *err = nil; [defaultManager copyItemAtPath: strResourcesBundle toPath:cacheStr error: &err]; if{ NSLog(@"复制初始资源文件出错:%@", err); } NSArray *contensArr= [NSArray arrayWithArray:[defaultManager contentsOfDirectoryAtPath:cacheStr error:nil]]; NSLog(@"%@",contensArr);
    

    wkwebview从tem目录下得到加载文件,生成url时选用fileU兰德猎豹CS6LWithPath

    NSString *cachesPath = NSTemporaryDirectory();//tem文件目录NSString *cacheStr=[NSString stringWithFormat:@"%@dist/index.html",cachesPath];NSURL *url=[NSURL fileURLWithPath: cacheStr];if (@available(iOS 9.0, *)) { [wkWebView loadFileURL:url allowingReadAccessToURL:url];} else { [wkWebView loadRequest:[NSURLRequest requestWithURL:url]];}
    

    获取沙盒地址的主意

    NSString *homeDir = NSHomeDirectory();// 获取沙盒主目录路径NSString *cachesPath = NSTemporaryDirectory();//tem文件目录NSString *cachesPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];//Documents文件目录
    

    10、WKWebView加载不受信任的https形成错误:参照他事他说加以调查

    - webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{ NSLog(@"didReceiveAuthenticationChallenge"); if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,card); }}
    

    11、WKWebView隐藏导航栏全屏加载,导航不可能手势再次回到难题,初叶以为与setAllowsBackForwardNavigationGestures手势争持形成,排查后发现是导航隐藏后不援帮手势重返,增添以下代码即可,更详细难点参谋小说第2点。

    隐身导航代码

    [self.navigationController setNavigationBarHidden:NO animated:NO];
    

    支撑手势再次来到代码

     self.navigationController.interactivePopGestureRecognizer.delegate = self; self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    

    12、WKWebView设置setAllowsBackForwardNavigationGestures手势再次回到事件监听方法:

    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    -gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{ return YES;}
    

    13、WKWebView在iOS第88中学使用允许手势重回会报错

    if (@available(iOS 9.0, *)) { [wkWebView setAllowsBackForwardNavigationGestures:true];} 
    

    14、WKWebview在iOS1第11中学的适配,顶上部分会让出情况栏中度

    if (@available(iOS 11.0, *)) { wkWebView.scrollView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;}
    
    if (@available(iOS 11.0, *)) { [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];}
    

    15、设置WKWebview是不是随键盘上移

    //设置wkwebview是否可以随着键盘往上移- viewForZoomingInScrollView:(UIScrollView *)scrollView{ if (isAllowScrollZoom) { return wkWebView; }else{ return nil; }}
    

    16、其余应用后台定位最上部蓝条,导致wkwebview页面向下移动

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeStatusBarFrame:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    - didChangeStatusBarFrame:(NSNotification *)notification{ NSValue *statusBarFrameValue = [notification.userInfo valueForKey:UIApplicationStatusBarFrameUserInfoKey]; NSLog(@"Status bar frame changed:%@", NSStringFromCGRect([statusBarFrameValue CGRectValue])); wkWebView.frame=CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);}
    

    17、wkwebview在iOS1第22中学键盘弹起页面不打消难题

    /// 监听将要弹起 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow) name:UIKeyboardWillShowNotification object:nil]; /// 监听将要隐藏 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden) name:UIKeyboardWillHideNotification object:nil];
    
    //iOS12中键盘弹起页面不收回问题#pragma mark - addObserverKeyboard/// 键盘将要弹起- keyBoardShow { CGPoint point = wkWebView.scrollView.contentOffset; keyBoardPoint = point;}/// 键盘将要隐藏- keyBoardHidden { wkWebView.scrollView.contentOffset = keyBoardPoint;}
    

    频频创新中...

    本文由新葡亰496net发布于奥门新萄京娱乐场,转载请注明出处:带你走进WKWebView的世界,剖析Android中webview和js之

    关键词:

上一篇:Swift语言学习,部分基础运算符

下一篇:没有了