这是一个Swift的错误? 在webView中打开一个文件

我开始通过这种新的语言工作,我喜欢很多…但它似乎是比我预期的buggier。

我在YouTube的一个简单的例子( https://www.youtube.com/watch?v=Rva9ylPHi2w )在根视图控制器中构build一个webView并加载一个网页。 这个例子适用于外部网页,但不是本地文件。 尝试打开本地文件时出现空白屏幕。

下面的代码是为ViewController.swift文件。

import UIKit class ViewController: UIViewController { @IBOutlet var WebView : UIWebView var URLPath = ""/files/test.html"" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. loadAddressURL() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadAddressURL() { let requestURL = NSURL (string:URLPath) let request = NSURLRequest(URL: requestURL) println("the requestURL is: \(requestURL)") WebView.loadRequest(request) } } 

你可以看到我添加了一个println来显示正在使用的URL请求,并向后显示:

用本地文件,我得到“requestURL是:/files/test.html”,这是我有位于示例html文件的位置。

是他们的东西我做错了,或者我应该与苹果?

这是我如何从本地文件加载HTML

  let bundle = NSBundle.mainBundle() var url = bundle.URLForResource("yourHTML", withExtension: "html"); var request = NSURLRequest(URL: url!); webContent.loadRequest(request) 

而不是使用该构造函数创buildNSURL ,而是使用[NSURL fileURLWithPath:]

你不能真正加载“本地文件”。 相反,请确保将您的文件添加到目标的“ Copy Bundle Resources构build阶段,然后向默认NSBundle询问其URL,例如:

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

如果文件位于项目组(黄色图标)文件中,则不必提供任何path信息,因为文件而不是项目组被复制。

如果文件位于文件夹引用(蓝色文件夹图标)中,则整个文件夹将被复制到该文件夹​​中。 在这种情况下,请使用URLForResource(, withExtension:, subdirectory:)或任何类似的方法。 (检查NSBundle的文档或头文件)

我是新手,所以不要相信我的代码

它看起来像它的工作,但它使我的xCode 6滞后(不寻常的)。我停下了AppleDev / Swift潜水( https://www.youtube.com/watch?v=Rva9ylPHi2w )给出的教程如果你把你的索引.html文件在您的应用程序的索引,这是使用的代码;

 import UIKit class ViewController: UIViewController { @IBOutlet weak var webview: UIWebView! let url = NSBundle.mainBundle().URLForResource("index", withExtension: "html") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. loadAddressURL() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadAddressURL() { let request = NSURLRequest(URL: url!) webview.loadRequest(request) } } 

该指数看起来有点像这样:

 Folder Project/app/ Folder Project/app/AppDelaget.swift Folder Project/app/ViewController.swift Folder Project/app/main.storybord Folder Project/app/index.html 

在Swift语言的UIWebView: –

请更新您的代码,并使用双引号将URLPath设置为这样

 var URLPath = "/files/test.html" 

您也可以使用此代码的WebView

 self.webView!.loadRequest(NSURLRequest(URL:NSURL(string:"https://www.google.com")))