简体   繁体   English

将 PathForResource 转换为字符串返回 nil Swift

[英]Converting PathForResource To String Returning nil Swift

When loading a local resource file in a mac app在 mac 应用程序中加载本地资源文件时

let urlpath = NSBundle.mainBundle().pathForResource("myResource", ofType: "html");

Converting the resource path to a string for NSURL always returns nil将资源路径转换为NSURLstring总是返回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)

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 ?这大概就是为什么我在pathForResource found nil while unwrapping an Optional valuefound nil while unwrapping an Optional value错误为found nil while unwrapping an Optional value我在这里缺少什么来正确地将pathForResource转换为string

if let myFileUrl = NSBundle.mainBundle().URLForResource("yourFile", withExtension: "html"){
            // do whatever with your url
} 

The code given in Leonardo's answer should work and is the easier and safer method with optional binding. Leonardo's answer中给出的代码应该可以工作,并且是具有可选绑定的更简单、更安全的方法。 Here is an explanation why your code fails:以下是您的代码失败的原因:

let requesturl = NSURL(string: urlpath!)

returns nil because urlpath is a file path and not an URL string (such as "file:///path/to/file").返回nil因为urlpath文件路径而不是URL 字符串(例如“file:///path/to/file”)。

If you replace that line with如果您将该行替换为

let requesturl = NSURL(fileURLWithPath: urlpath!)

then you will get the expected output.然后你会得到预期的输出。

For Swift 5对于 Swift 5

let path = Bundle.main.path(forResource: "myResource", ofType: "html")
let url = URL(fileURLWithPath: path!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM