使用Swift将本地HTML加载到UIWebView中


75

今天早上,这使我发疯。我想将一些本地html加载到Web视图中:

class PrivacyController: UIViewController {

    @IBOutlet weak var webView:UIWebView!

    override func viewDidLoad() {
        let url = NSURL(fileURLWithPath: "privacy.html")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
}

该html文件位于我的项目的根文件夹中,但在组中。Webview对我来说是空白的。有什么想法怎么了?我使用的是xcode 6.1,并在iPhone 6上运行了此示例。


Answers:


81

要检索应用程序资源的URL,应使用以下URLForResource方法NSBundle类的。

迅捷2

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

迅捷3

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

重点在于,它必须是“ privacy”而不是“ privacy.html”。这就是为什么它对我不起作用的原因。
2014年

只是添加..在Swift 4及更高版本上可以完美工作
androCoder-BD

27

斯威夫特3:键入安全

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Adding webView content
    do {
        guard let filePath = Bundle.main.path(forResource: "myFile", ofType: "html")
            else {
                // File Error
                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")
    }
}

请记住:NS =不迅速:]


感谢您@Peter Kreinz
塞巴斯蒂安REMY

为什么第一次加载需要几秒钟?
Codetard

17
// Point UIWebView
@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    //load a file
    var testHTML = NSBundle.mainBundle().pathForResource("privacy", ofType: "html")
    var contents = NSString(contentsOfFile: testHTML!, encoding: NSUTF8StringEncoding, error: nil)
    var baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file

    webView.loadHTMLString(contents, baseURL: baseUrl)

}

11

斯威夫特33:)

if let url = Bundle.main.url(forResource: "privacy", withExtension: "html") {
    webview.loadRequest(URLRequest(url: url))
}

9

Swift 2.1版

这种情况还包括编码

// load HTML String with Encoding
let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html")
do {
    let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
    webView.loadHTMLString(fileHtml as String, baseURL: nil)
}
catch {

}

8

将本地HTML文件添加到您的项目中,并将该文件命名为home.html,然后使用NSURL对象创建NSURLRequest。在将请求传递到Web视图之后,它将把请求的URL加载到Web视图中,如果不使用情节提要,则将uiwebview添加到视图控制器视图中,如以下代码所示。 

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
        let myRequest = NSURLRequest(URL: localfilePath!);
        myWebView.loadRequest(myRequest);
        self.view.addSubview(myWebView)
    }

有关更多参考,请参考此http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/


5

这为我工作:

@IBOutlet weak var mWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    mWebView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fineName", ofType: "html")!)))

}

新增App Transport Security SettingsDictionary的Info.plist文件。还Allow Arbitrary LoadsApp Transport Security设置添加了类型Boolean和值的子项YES

是教程。

已编辑

对于Swift 3(Xcode 8)

mWebView.loadRequest(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "test/index", ofType: "html")!)))

3

您可以在UIWebView中加载html字符串或本地html文件。

HTML字符串:

func loadHtmlCode() {
    let htmlCode = "<html><head><title>Wonderful web</title></head> <body><p>wonderful web. loading html code in <strong>UIWebView</strong></></body>"
    webView.loadHTMLString(htmlCode, baseURL: nil)
}

HTML档案:

func loadHtmlFile() {
    let url = NSBundle.mainBundle().URLForResource("contactus", withExtension:"html")
    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
}

可以在这里找到详细信息:http : //webindream.com/load-html-uiwebview-using-swift/


如何在loadHtmlCode()中显示图像,因为我尝试过但是图像为空,显示@farhad rubel
Dilip Tiwari

我试图这样让htmlCode =“ <html> <head> <title> Wonderful web </ title> </ head> <body bgcolor = orange> <p> wonderful web。在<strong> UIWebView </ strong>中加载html代码> </ p> <p> <img src = chania.jpg width = 200 height = 200> </ p> </> </ body>”
Dilip Tiwari

3

这是Swift 4的简洁版本

1)添加导入 import WebKit

2)添加WebKit.framework您的项目

在此处输入图片说明

@IBOutlet weak var webView: WKWebView!

if let filePath = Bundle.main.url(forResource: "FILE_NAME", withExtension: "html") {
  let request = NSURLRequest(url: filePath)
  webView.load(request as URLRequest)
}

2

快速3请使用以下命令:

do
    {
        let testHTML = Bundle.main.path(forResource: "about", ofType: "html")
        let contents =  try NSString(contentsOfFile: testHTML!, encoding: String.Encoding.utf8.rawValue)
        let baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file

        mWebView.loadHTMLString(contents as String, baseURL: baseUrl as URL)
    }
    catch
    {

    }

1

Swift 4.2,Xcode 10.1,WKWebView从文件加载HTML。不推荐使用UIWebView。

在运行于iOS 8及更高版本中的应用程序中,请使用WKWebView类,而不要使用UIWebView。

import WebKit

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let localFilePath = Bundle.main.url(forResource: "document_terms_of_use", withExtension: "html")
    let request = NSURLRequest(url: localFilePath!)
    webView.load(request as URLRequest)
}

1

快速4.2和5:

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768))
let url = URL(string: PERS_Path)
webView?.navigationDelegate = self
webView?.uiDelegate = self
webView!.loadFileURL(url!, allowingReadAccessTo: url!)
self.view. addSubview(webView)

别忘了添加 WKNavigationDelegate, WKUIDelegate


0

这对我有用(Xcode 8,Swift 3)

@IBOutlet弱var webViewer:UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let localfilePath = Bundle.main.url(forResource: "homeInfo", withExtension: "html");
    let myRequest = NSURLRequest(url: localfilePath!);
    webViewer.loadRequest(myRequest as URLRequest);
    self.view.addSubview(webViewer)
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.