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

时间:2022-09-04 08:06:31

This one is driving me crazy early this morning. I want to load some local html into a web view:

今天早上这个让我抓狂。我想在web view中加载一些本地html:

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

The html file is located in the root folder of my project but is inside a group. The webview is blank for me. Any ideas whats wrong? I am on xcode 6.1 and running this example on my iphone 6.

html文件位于项目的根文件夹中,但在组中。webview对我来说是空白的。任何想法是什么错了吗?我使用的是xcode 6.1,在我的iphone 6上运行这个示例。

10 个解决方案

#1


55  

To retrieve URLs for application resources, you should use URLForResource method of NSBundle class.

要检索应用程序资源的url,应该使用NSBundle类的URLForResource方法。

Swift 2

斯威夫特2

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

Swift 3

斯威夫特3

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

#2


15  

// 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


14  

Swift 3: type safe

斯威夫特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")
    }
}

Keep in mind: NS = Not Swift :]

记住:NS = Not Swift:]

#4


6  

Add the local html file into your project name it as home.html, then create the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview and if you are not using storyboard add the uiwebview into viewcontroller view like the below code. 

将本地html文件作为home添加到项目名称中。html,然后使用NSURL对象创建NSURLRequest,然后将请求传递给webview它会将请求的URL加载到webview中,如果你不使用storyboard,将uiwebview添加到viewcontroller视图中,如下代码所示。

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

For more reference please refer this http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

更多的参考请参考http://sourcefreeze.com/uiwebview-example- using-swif- in-ios/

#5


6  

Swift version 2.1

斯威夫特2.1版本

this case also include Encoding

这种情况还包括编码

// 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 {

}

#6


4  

This is worked for me:

这对我有用:

@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")!)))

}

Added App Transport Security Settings with Dictionary type in info.plist file. Also added sub key Allow Arbitrary Loads for App Transport Security Settings with type Boolean and value YES.

在info中添加了带有字典类型的应用程序传输安全设置。plist文件。此外,还增加了子键,允许使用类型布尔值和值的应用程序传输安全设置的任意负载。

Here is tutorial.

下面是教程。

EDITED

编辑

For Swift 3 (Xcode 8)

Swift 3 (Xcode 8)

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

#7


3  

Swift 3 with 3 lines :)

Swift 3, 3行:)

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

#8


1  

You can load html string or local html file in UIWebView.

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

HTML string:

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 file:

HTML文件:

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

Details can be found here: http://webindream.com/load-html-uiwebview-using-swift/

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

#9


0  

This worked for me (Xcode 8, Swift 3)

(Xcode 8, Swift 3)

@IBOutlet weak var webViewer: UIWebView!

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

#10


0  

For swift 3 Use this:

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
    {

    }

#1


55  

To retrieve URLs for application resources, you should use URLForResource method of NSBundle class.

要检索应用程序资源的url,应该使用NSBundle类的URLForResource方法。

Swift 2

斯威夫特2

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

Swift 3

斯威夫特3

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

#2


15  

// 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


14  

Swift 3: type safe

斯威夫特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")
    }
}

Keep in mind: NS = Not Swift :]

记住:NS = Not Swift:]

#4


6  

Add the local html file into your project name it as home.html, then create the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview and if you are not using storyboard add the uiwebview into viewcontroller view like the below code. 

将本地html文件作为home添加到项目名称中。html,然后使用NSURL对象创建NSURLRequest,然后将请求传递给webview它会将请求的URL加载到webview中,如果你不使用storyboard,将uiwebview添加到viewcontroller视图中,如下代码所示。

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

For more reference please refer this http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

更多的参考请参考http://sourcefreeze.com/uiwebview-example- using-swif- in-ios/

#5


6  

Swift version 2.1

斯威夫特2.1版本

this case also include Encoding

这种情况还包括编码

// 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 {

}

#6


4  

This is worked for me:

这对我有用:

@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")!)))

}

Added App Transport Security Settings with Dictionary type in info.plist file. Also added sub key Allow Arbitrary Loads for App Transport Security Settings with type Boolean and value YES.

在info中添加了带有字典类型的应用程序传输安全设置。plist文件。此外,还增加了子键,允许使用类型布尔值和值的应用程序传输安全设置的任意负载。

Here is tutorial.

下面是教程。

EDITED

编辑

For Swift 3 (Xcode 8)

Swift 3 (Xcode 8)

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

#7


3  

Swift 3 with 3 lines :)

Swift 3, 3行:)

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

#8


1  

You can load html string or local html file in UIWebView.

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

HTML string:

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 file:

HTML文件:

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

Details can be found here: http://webindream.com/load-html-uiwebview-using-swift/

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

#9


0  

This worked for me (Xcode 8, Swift 3)

(Xcode 8, Swift 3)

@IBOutlet weak var webViewer: UIWebView!

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

#10


0  

For swift 3 Use this:

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
    {

    }