0
votes

I have HTML pages load from the local app "Documents" folder, with structured directories. The "main" folder store home page and resource, an "interactive" folder store another module, through homepage to redirect.

enter image description here

I load the "ipad.html" in "main" folder, the page cannot load resources (i.e. css / js files) to display correct style. The code like this.

let indexHTML = "ipad.html"
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath: String = path[0]
let folderPath = documentDirectoryPath.appending("/main")
let destinationURLForFile = URL(fileURLWithPath: folderPath + "/\(indexHTML)")
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)

do{
    let fileName =  try String(contentsOf: destinationURLForFile, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    webView.loadHTMLString(fileName, baseURL: baseUrl)

}catch{
    print("Loading HTML failed.")
}

Inside "ipad.html" like this.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>demo</title>
    <meta name="description" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <link rel="stylesheet" href="./css/animate.min.css">
    <link rel="stylesheet" href="./css/style.css">

    <script src="./bower_components/modernizr/modernizr-2.5.3.min.js"></script>
</head>
<body class="page-ipad-landing animated" lang="">
......
......
</body>
</html>

But I move it to Bundle.main, and remove "main" folder to load the "ipad.html" is display correctly. Why it different behavior or iOS not support complex folder structure under "Documents" folder and how should I correct it? Thanks.

This simple one is work properly in Bundle.main folder.

if let url = Bundle.main.url(forResource: "ipad", withExtension: "html") {
  do {
       let contents = try String(contentsOfFile: url.path)
       webView.loadHTMLString(contents, baseURL: url.deletingLastPathComponent())
  } catch {
     print("Could not load the HTML string.")
  }
}
1

1 Answers

0
votes

Add all the HTML directories & files in your project.

let webView = WKWebView()
if let htmlPath = Bundle.main.path(forResource: "directory/index", ofType: "html") {
  let htmlUrl = URL(fileURLWithPath: htmlPath, isDirectory: false)
  webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
  view = webView
}

enter image description here