WKWebView加载Web本地项目实践(Swift)

发布于:2023-01-09 ⋅ 阅读:(453) ⋅ 点赞:(0)

Demo环境:

IOS 15,Xcode 13, swift, vue打包后的dist文件

步骤:

一:将web项目打包后的dist目录下文件移动到ios项目中

在这里插入图片描述
新建Resources文件夹
在这里插入图片描述
注意选种第二种方式
在这里插入图片描述
在这里插入图片描述
查看Build Phases中可以看到,web资源已被自动添加
在这里插入图片描述

二: Swift代码

//
//  ViewController.swift
//  WebDemo
//
//  Created by admin on 2022/8/20.
//

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    
    let fullScreenSize = UIScreen.main.bounds.size
    var myWebView :WKWebView!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs") // 解决web同源策略问题
        myWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: fullScreenSize.width, height: fullScreenSize.height),configuration: webConfiguration)

        
        myWebView.navigationDelegate = self
        
        
        self.view.addSubview(myWebView)

        
        let myPath = Bundle.main.path(forResource: "index", ofType: "html")
        let myURL = URL(fileURLWithPath: myPath!)
        
    
        myWebView.loadFileURL(myURL, allowingReadAccessTo: Bundle.main.bundleURL)
    }
   
}

三:效果图

在这里插入图片描述
点个赞再走吧!😁


网站公告

今日签到

点亮在社区的每一天
去签到