使用swift将本地html加载到UIWebView中

时间:2014-10-30 07:39:13

标签: ios swift uiwebview

今天早上这个让我疯狂。我想将一些本地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上运行这个例子。

13 个答案:

答案 0 :(得分:72)

要检索应用资源的网址,您应该使用URLForResource类的NSBundle方法。

Swift 2

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

Swift 3

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

答案 1 :(得分:22)

Swift 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 = Not Swift:]

答案 2 :(得分: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)

}

答案 3 :(得分:10)

Swift 3 3 :)

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

答案 4 :(得分:8)

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 {

}

答案 5 :(得分:7)

将本地HTML文件添加到项目中并将该文件命名为home.html,然后使用NSURL对象创建NSURLRequest。在将请求传递给Web视图之后,它会将请求的URL加载到Web视图中,如果您不使用storyboard,请将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/

答案 6 :(得分: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")!)))

}

info.plist 文件中添加了App Transport Security Settings Dictionary类型。还为应用传输安全设置添加了子键Allow Arbitrary Loads,类型为Boolean,值为YES

Here是教程。

<强> EDITED

对于Swift 3(Xcode 8)

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

答案 7 :(得分: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/

答案 8 :(得分:2)

这是 Swift 4

的简洁版本

1)添加导入import WebKit

2)在项目中添加WebKit.framework

enter image description here

@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)
}

答案 9 :(得分:1)

对于swift 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
    {

    }

答案 10 :(得分:0)

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

@IBOutlet weak 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)
}

答案 11 :(得分:0)

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)
}

答案 12 :(得分:0)

swift 4.2和5:

  digraph {
      rankdir=TB;
      newrank = true;
      ...

不要忘记添加此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)