【问题标题】:Webview application in Swift 4.2Swift 4.2 中的 Webview 应用程序
【发布时间】:2019-01-21 09:56:28
【问题描述】:

我正在尝试加载位于我的本地目录中的 HTML 页面。它向我显示了这个错误 “加载失败:数据/Anctors.json” 此外,此页面在 Firefox 上运行良好,但在 Google Chrome 上无法运行。 我的代码:

var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
    let url = URL(string: "file:///Users/rashid/Documents/Developers/Swift/www/index.html")!
    webView.load(URLRequest(url: url))

    let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
    toolbarItems = [refresh]
    navigationController?.isToolbarHidden = false
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
}

【问题讨论】:

标签: ios swift uiwebview


【解决方案1】:

您必须使用Bundle.main.url(forResource: <#T##String?#>, withExtension: <#T##String?#>) 方法从应用程序内加载资源 请参阅以下链接以获取更详细的答案(可能重复)

[1]: https://stackoverflow.com/questions/26647447/load-local-html-into-uiwebview-using-swift

【讨论】:

  • "file:///Users/rashid/Documents/Developers/Swift/www/index.html" 这是我的文件 url 路径
  • 这是我拥有所有 html 文件和文件夹的绝对路径
  • 试试这个 - Bundle.main.url(forResource: "index", withExtension: "html")
  • 将 index.html 拖放到 Xcode 中的项目下方,如果需要,选中 Copy item 并尝试相同的代码
【解决方案2】:

请添加此代码以允许来自文档目录的内容:

self.webView.loadFileURL( htmlfilePath, allowingReadAccessTo: documentDirUrl)

并确保您的 html 文件和其他内容都在同一个目录中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 2014-05-17
    • 2023-03-31
    相关资源
    最近更新 更多