ios 使用 swift 将本地 html 加载到 UIWebView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26647447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load local html into UIWebView using swift
提问by Upvote
This one is driving me crazy early this morning. I want to load some local html into a web view:
今天一大早就让我发疯了。我想将一些本地 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)
}
}
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 文件位于我的项目的根文件夹中,但在一个组内。网络视图对我来说是空白的。任何想法有什么问题?我在 xcode 6.1 上并在我的 iphone 6 上运行这个例子。
回答by rintaro
To retrieve URLs for application resources, you should use URLForResource
method of NSBundle
class.
要检索应用程序资源的 URL,您应该使用类的URLForResource
方法NSBundle
。
Swift 2
斯威夫特 2
let url = NSBundle.mainBundle().URLForResource("privacy", withExtension:"html")
Swift 3
斯威夫特 3
let url = Bundle.main.url(forResource: "privacy", withExtension: "html")
回答by Sébastien REMY
Swift 3: type safe
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")
}
}
Keep in mind: NS = Not Swift :]
请记住:NS = 不是 Swift :]
回答by Jupiter Cls
// 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)
}
回答by MBH
Swift 3with 3lines :)
斯威夫特3与3行:)
if let url = Bundle.main.url(forResource: "privacy", withExtension: "html") {
webview.loadRequest(URLRequest(url: url))
}
回答by Sruit A.Suk
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 {
}
回答by Bharathi Devarasu
Add the local HTML file into your project and name that file as home.html, then create the NSURLRequest using NSURL object. After that passing the request to web view it will load the requested URL into web view and if you are not using storyboard add the uiwebview into view controller view like the below code.?
将本地 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)
? ? }
For more reference please refer this http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/
如需更多参考,请参阅此http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/
回答by Abduhafiz
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.plistfile. Also added sub key Allow Arbitrary Loads
for App Transport Security Settingswith type Boolean
and value YES
.
在info.plist文件中添加App Transport Security Settings
了Dictionary
类型。还增加子键的应用交通运输安全设置与类型和价值。Allow Arbitrary Loads
Boolean
YES
Hereis 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")!)))
回答by farhad rubel
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/
回答by Aamir
Here is succinct version for Swift 4
这是Swift 4 的简洁版本
1) Add import import WebKit
1) 添加导入 import WebKit
2) Add WebKit.framework
in your project
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)
}
回答by Zouhair Sassi
swift 4.2 & 5:
快速 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)
don't forget to add this WKNavigationDelegate, WKUIDelegate
不要忘记添加这个 WKNavigationDelegate, WKUIDelegate