skip to Main Content

I found a code to read html files with swift playground for ipad. But nothing showed up in the App Preview and I got error message : Cannot convert value of type ‘URL’ to expertes argument type ‘String’ . Can you help me because I don’t know where the problem comes from. Here is my code

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
    }
    
    
}

Need help to read html files with Swift Playgrounds for iPad

2

Answers


  1. Chosen as BEST ANSWER

    Thank you it’s work well. The index.html showed up but not images (inside html file) in ressources. Maybe I made a mistake or I have to do another way?


  2. Replace this line let htmlPath = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www") with this 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
    }
    
    
    }
    

    Or You can change to this if you want.

        let htmlPath = Bundle.main.url(forResource: "index", withExtension: "html")
        webView.loadFileURL(htmlPath!, allowingReadAccessTo: htmlPath!.deletingLastPathComponent())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search