You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为iOS WKWebView加载的本地内容设置自定义Base URL?

Setting a Custom Base URL for WKWebView Loading Local HTML

Absolutely! You can fix that annoying long simulator file path issue by setting a custom base URL for your WKWebView. This will make your JavaScript routing logic work with clean URLs like https://app.mr.dk/ instead of the messy simulator path. Here's how to adjust your code:

Step 1: Read the local HTML file content

Instead of using loadFileURL, we'll first read the raw HTML content from your file. This lets us specify our own base URL when loading it:

guard let htmlFilePath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "iosbuild"),
      let htmlContent = try? String(contentsOfFile: htmlFilePath, encoding: .utf8) else {
    // Handle the error if the file can't be found or read
    print("Failed to load local HTML file")
    return
}

Step 2: Define your custom base URL

Create a URL object with your desired base address. Make sure to include a protocol (http/https)—WKWebView requires this to properly resolve relative paths for resources like CSS, JS, or images:

let customBaseURL = URL(string: "https://app.mr.dk/")!

Step 3: Load the HTML with the custom base URL

Use loadHTMLString instead of loadFileURL, passing in the HTML content and your custom base URL:

webView.loadHTMLString(htmlContent, baseURL: customBaseURL)

Why this works

When your JavaScript code checks window.location or uses routing logic, it will now see URLs rooted at https://app.mr.dk/ instead of the long simulator file path. Plus, any relative resource links in your HTML (like <script src="./app.js"> or <img src="./assets/logo.png">) will still work correctly—WKWebView will automatically map these relative paths to the actual local files in your app bundle.

Quick note

If you need to restrict access to specific local directories (like you did with allowingReadAccessTo in your original code), this approach still respects the app bundle's file access rules, so you don't have to worry about extra permissions issues.

内容的提问来源于stack exchange,提问作者Marc Rasmussen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:17:42