无法在 swift 4 中加载本地 html 文件
Posted
技术标签:
【中文标题】无法在 swift 4 中加载本地 html 文件【英文标题】:unable to load local html file in swift 4 【发布时间】:2017-10-09 10:51:03 【问题描述】:始终在文件路径中存储 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")
【问题讨论】:
你能显示你的错误吗? 没有错误,但总是在文件路径中存储 nil 我必须使用构建阶段添加我的 html 文件 【参考方案1】: 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))
【讨论】:
以上是关于无法在 swift 4 中加载本地 html 文件的主要内容,如果未能解决你的问题,请参考以下文章
来自html字符串的iOS Swift 4图像未在WKWebView中加载
Swift 4:无法在包中加载 NIB:自定义 UITableViewCell 的“NSBundle”(无 IB)
我想在 html 中加载一个 json 脚本(本地),用作表格