您的位置:首页 > 移动开发 > Swift

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

2018-01-21 00:00 1616 查看
最近一个项目需要用 iOS 加载网页,下面简单记录一下WKWebView加载本地html 文件;

ViewController.swift

//
//  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.html

<!--引入外部 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;

}

效果展示:

点击前:



点击后:



xcode 打印:



这里面要注意的是 html 路径,我在这儿坑了好久。。。~~!



主要是 bundle resources ,如果在 Xcode 中右键添加文件 这里会自动加上

这里的bundle 是 main bundle,网上说使用自定义bundle会更好,后面有时间了在研究吧,

感觉 swift 比 OC 还。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios webview swift