将PathForResource转换为返回nil Swift的字符串 [英] Converting PathForResource To String Returning nil Swift
问题描述
在Mac应用程序中加载本地资源文件时
When loading a local resource file in a mac app
let urlpath = NSBundle.mainBundle().pathForResource("myResource", ofType: "html");
将资源路径转换为NSURL
的string
总是返回nil
Converting the resource path to a string
for NSURL
always returns nil
println("resource path = \(urlpath)") <---resource logged ok
web.frameLoadDelegate = self;
let requesturl = NSURL(string: urlpath!)
println("URL String = \(requesturl)"),<---- returns nil
let request = NSURLRequest(URL: requesturl!)
web.mainFrame.loadRequest(request)
大概是为什么我收到错误found nil while unwrapping an Optional value
的原因
我在这里想将pathForResource
正确转换为string
的什么?
Which presumably is why im getting the error found nil while unwrapping an Optional value
What am I missing here to correctly convert the pathForResource
to a string
?
推荐答案
莱昂纳多答案中给出的代码应该有效,并且更容易,更安全. 可选绑定的方法.这是为什么您的解释 代码失败:
The code given in Leonardo's answer should work and is the easier and safer method with optional binding. Here is an explanation why your code fails:
let requesturl = NSURL(string: urlpath!)
返回nil
,因为urlpath
是文件路径,而不是 URL字符串
(例如"file:///path/to/file").
returns nil
because urlpath
is a file path and not an URL string
(such as "file:///path/to/file").
如果将该行替换为
let requesturl = NSURL(fileURLWithPath: urlpath!)
然后您将获得预期的输出.
then you will get the expected output.
这篇关于将PathForResource转换为返回nil Swift的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!