始终在文件路径中存储nil我在项目根目录中有我的html文件
let myWebView:UIWebView = UIWebView(frame: CGRect(x:0, y:0, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height))
self.view.addSubview(myWebView)
do {
guard let filePath = Bundle.main.path(forResource: "iphone_help", ofType: "html")
else {
print ("File reading error")
return
}
let contents = try String(contentsOfFile: filePath, encoding: .utf8)
let baseUrl = URL(fileURLWithPath: filePath)
webView.loadHTMLString(contents as String, baseURL: baseUrl)
}
catch {
print ("File HTML error")
}
答案 0 :(得分:0)
func loadWebView(htmlString : String) {
//Give HTML file a name:
//Constants.kTempFiled
let htmlFileName: NSString = "file.html"
//Create a reference to the temporary directory that will store the HTML file:
let tempDirectory: NSString = NSTemporaryDirectory() as NSString
//Append reference temporary directory to include HTML file name:
let htmlFilePath: NSString = tempDirectory.appendingPathComponent(htmlFileName as String) as NSString as NSString
//Convert appended temporary directory NSString to an NSURL object:
let htmlUrl = NSURL(fileURLWithPath: htmlFilePath as String)
//Below, HTML string is written to a file:
do { try htmlString.write(toFile: htmlFilePath as String, atomically: true, encoding: String.Encoding.utf8) }
catch { }
//HTML file URL is fetched and displayed in UIWebView:
webView.loadRequest(NSURLRequest(URL: htmlUrl))
}