iOS WKWebView 加載本地html文件(swift)

 

最近一個項目須要用 iOS 加載網頁,下面簡單記錄一下WKWebView加載本地html 文件;javascript

 

ViewController.swiftcss

//
//  ViewController.swift
//  jmj_storeshow
//
//  Created by dubox on 2018/1/16.
//  Copyright © 2018年 dubox. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController , WKUIDelegate{

    var webView: WKWebView!
   
    
    override func loadView() {
        
        let conf = WKWebViewConfiguration()
        conf.userContentController = WKUserContentController()
        conf.preferences.javaScriptEnabled = true
        conf.selectionGranularity = WKSelectionGranularity.character
        conf.allowsInlineMediaPlayback = true
        //註冊 js 消息通道
        conf.userContentController.add(self , name: "msgBridge")
        
        webView = WKWebView(frame: .zero, configuration: conf)  //.zero
        webView.uiDelegate = self
        //禁止頂部下拉 和 底部上拉效果
        webView.scrollView.bounces = false
        //解決全屏播放視頻 狀態欄閃現致使的底部白條  never:表示不計算內邊距
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /**加載 https 連接  **/
        //let myURL = URL(string: "http://192.168.2.186:8080")
        //let myRequest = URLRequest(url: myURL!)
        //webView.load(myRequest)
        
        /**加載本地 HTML文件**/
            //從主Bundle獲取 HTML 文件的 url
        let fileURL =  Bundle.main.url(forResource: "dist/index", withExtension: "html" )
        webView.loadFileURL(fileURL!,allowingReadAccessTo:Bundle.main.bundleURL);
        
        /**加載 html 內容**/
        //webView.loadHTMLString("<h1>h1</h1><img src='.html/images/h.png'>", baseURL: Bundle.main.bundleURL);
    }
    
   

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}

extension ViewController: WKNavigationDelegate {
    
}

//js 和 swift 的交互
extension ViewController: WKScriptMessageHandler {
    
    //接收 js 發來的消息
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        //判斷消息通道
        if(message.name == "msgBridge"){
            //TODO ...
            //message.body(any 類型) 即前端 js 傳來的數據,若是傳字符串這裏接收的就是字符串,若是傳 json 對象或 js 對象 則這裏是 NSDictionary
            print(message.body)
            let msg = message.body as! NSDictionary;
            
            //swift 調 js函數
            webView.evaluateJavaScript("funcforswift('\( msg["msg"]  as! String)')", completionHandler: {
                (any, error) in
                if (error != nil) {
                    print(error ?? "err")
                }
            })
        }
        
    }
}

index.htmlhtml

<!--引入外部 css-->
<link  rel="stylesheet" type="text/css" href="css/test.css"/>
<script>
    //測試內嵌 js
    document.write('kkk');
    document.getElementById('h').style="color:red;";
    
    alert('aa');  //alert在 WKWebView 中沒效果
</script>
<h1 id="h">
    hello word
    </h1>

<img src="images/h.png">
    
    <!--引入外部 js-->
<script src="js/test.js"></script>


<!--
 
 這裏全部引入的文件 css、js、img  都須要相對路徑,
 包括 css 文件中引入的圖片、字體等
 -->

 

 

test.js前端

document.getElementById('h').onclick = function(){
    //向 swift 發送數據,這裏的‘msgBridge’就是 swift 中添加的消息通道的 name
    window.webkit.messageHandlers.msgBridge.postMessage({"msg":"#test msg"});
}


//這是一個普通的 js 函數,將在 swift 中調用該函數
function funcforswift(msg){
    
    document.getElementById('h').innerText+=msg;
    
}

效果展現:java

點擊前:web

點擊後:json

xcode 打印:swift

 

 

 

這裏面要注意的是 html 路徑,我在這兒坑了很久。。。~~!xcode

主要是 bundle resources ,若是在 Xcode 中右鍵添加文件 這裏會自動加上ide

這裏的bundle 是 main bundle,網上說使用自定義bundle會更好,後面有時間了在研究吧,

感受 swift 比 OC 還。。。

相關文章
相關標籤/搜索