swift - 在 UIWebView 中加载本地 HTML 文件

标签 swift uiwebview swift2

我在加载本地 HTML 文件时遇到问题。这是我的代码。请帮忙。

let URL = NSBundle.mainBundle().pathForResource("index2", ofType: "html")
let request = NSURLRequest(URL: url!)
Webview.loadRequest(request)

使用以下代码。我已设法加载 html 文件,但它没有加载 CSS!

让 htmlFile = NSBundle.mainBundle().pathForResource("index1", ofType: "html") 让 html = 试试?字符串(contentsOfFile:htmlFile!,编码:NSUTF8StringEncoding) GSFWebView.loadHTMLString(html!, baseURL: nil)

最佳答案

只需将这段代码写在你的 ViewDidLoad 中,我已经添加了这个页面的 url 作为示例,只需将其替换为你的。在 Storyboard 上,您无需执行任何操作,如果您在 View Controller 上添加了任何额外的 View 作为网站的容器,则将我的代码中的 self.view 替换为您的 View 。

    let myWebView:UIWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
    //add your url on line below
    myWebView.loadRequest(URLRequest(url: URL(string: "https://stackoverflow.com/questions/26647447/load-local-html-into-uiwebview-using-swift")!))
    self.view.addSubview(myWebView)

如果你想从本地文件加载页面,你可以通过这种方式定义 url 来实现。

swift 2

  let url = NSBundle.mainBundle().URLForResource("webFileName", withExtension:"html") 

swift 3

  let url = Bundle.main.url(forResource: "webFileName", withExtension: "html")

关于swift - 在 UIWebView 中加载本地 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749253/

相关文章:

arrays - 将任何对象作为参数的 Swift 数组的扩展函数

swift - 为什么访问具有父关系的子类 NSManagedObject 的字符串参数会崩溃?

ios - 根据对象参数 UPDATED Swift 从提取中删除重复对象

xcode - 成功登录网站后如何重定向到新网址?

iphone - UIWebView 链接在 Safari 中打开

ios - 无法使用 swift 2 在 IOS9 上的 webview 中加载 http 授权网站 url

swift - libswiftFoundation.dylib 和 libswiftcore.dylib 是做什么的?

swift - 是否可以在 firestore 查询上有一个完成 block ?

ios - 如何获取 CGPDFDictionaryRef 键

ios - 如何删除自定义uiview中的边框线?