需要知道如何使用iPad的Swift Playgrounds应用程序读取HTML文件

643ylb08  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(137)

我发现了一个代码,可以用iPad的swift playground读取html文件。但没有出现在应用程序预览,我得到了错误消息:无法将类型“URL”的值转换为expertes参数类型“String”。我不知道问题出在哪里,你能帮帮我吗?这是我的代码

import SwiftUI
import WebKit

struct ContentView: View {
    
    var body: some View {
        VStack {
            WebView()
            
        }
        
        
        
    }
}

struct WebView:UIViewRepresentable{
    func makeUIView(context: Context) -> some UIView {
        let webView = WKWebView()
          
        let htmlPath = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www")
        
        
        let htmlUrl = URL(fileURLWithPath: htmlPath)
        
     
        webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl.deletingLastPathComponent())
        
        return webView
    }
    
    
}

需要帮助来读取iPad版Swift Playgrounds的html文件

ajsxfq5m

ajsxfq5m1#

将此行let htmlPath = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www")替换为此guard let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") else { return webView }

import SwiftUI
import WebKit

struct WebView:UIViewRepresentable{
func updateUIView(_ uiView: UIViewType, context: Context) {
    
}

func makeUIView(context: Context) -> some UIView {
    let webView = WKWebView()
      
    guard let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") else { return webView }
    
    
    let htmlUrl = URL(fileURLWithPath: htmlPath!)
    
 
    webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl.deletingLastPathComponent())
    
    return webView
}

}

或者如果你想的话你可以换成这个。

let htmlPath = Bundle.main.url(forResource: "index", withExtension: "html")
    webView.loadFileURL(htmlPath!, allowingReadAccessTo: htmlPath!.deletingLastPathComponent())

相关问题