Search code examples
htmliosswiftswiftuiwkwebview

Swift: How do I navigate to an HTML bookmark using # tags using WKWebView?


I am trying to load an HTML file using WKWebView, but I would like my app to go to specific points in the webpage. The HTML itself contains <a name="bookmark7"> tags throughout. If I were to use a browser, I would just append the link name using # directly after the filename as so: http://mywebsite.com/index.html#bookmark1

I have tried the following to no avail:

let bookmark = "#bookmark1"
let url = Bundle.main.url(forResource: "index", withExtension: "html\(bookmark)", subdirectory: "website")!
uiView.loadFileURL(url, allowingReadAccessTo: url)

This gave me a preview error and would not load. How can I jump to a specific point in an HTML page? Any method will do. The full SwiftUI View is below:

import SwiftUI
import WebKit

struct CodeView: View {
    
    
    var body: some View {
        WebView()
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
    }
}

struct WebView: UIViewRepresentable {
    
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        
        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
        uiView.loadFileURL(url, allowingReadAccessTo: url)
    }
}

struct CodeView_Previews: PreviewProvider {
    static var previews: some View {
        CodeView()
    }
}

Solution

  • Here is working variant (tested with Xcode 12 / iOS 14)

    func updateUIView(_ uiView: WKWebView, context: Context) {
        guard let resourceURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website") else { return }
    
        let path = resourceURL.absoluteString + "#bookmark1"
        if let url = URL(string: path) {
            uiView.loadFileURL(url, allowingReadAccessTo: url)
        }
    }