pyList

IOS WKWebView 灵活载入本地文件和网络文件

有个小需求,做个简单的 IOS APP,其实就是一个WebView,并且优先载入指定网址,如果载入失败就加载本地静态文件。

IOS WKWebView 灵活载入本地文件和网络文件

第一次玩,利用Google 还是顺利完成,记一下结果,下面是官方的示例:

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
    
    var webView: WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myURL = URL(string:"https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

在此基础上添加事件的响应,这里WKNavigationDelegateWKUIDelegate 区别,前者主要处理一些跳转、加载处理操作,后者主要处理JS脚本,确认框,警告框等,为了监听页面的载入情况,使用WKNavigationDelegate。全部代码:

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate { 
    
    var webView: WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 载入空白页
        webView.loadHTMLString("<html><body><p>blank</p></body></html>", baseURL: nil)
        
        let myURL = URL(string:"https://www.google.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        
    }
    
    //web view start loading
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Strat loading")
    }
    
    //web view finish loading
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("finish loading")
    }
    
    //handle error
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "Website")!
        webView.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        webView.load(request)
    }
}

静态文件目录结构:

Website/
├── app.js
├── clipboard.min.js
├── index.html
├── styles.css
└── tachyons.min.css

参考

本文标签: IOS WebView Swift SPA xcode
本文网址: https://pylist.com/t/1555851586 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
发表第一条评论!
验证码图片
相关推荐