【问题标题】:Converting PathForResource To String Returning nil Swift将 PathForResource 转换为返回 nil Swift 的字符串
【发布时间】:2015-02-25 21:59:09
【问题描述】:

在 mac 应用中加载本地资源文件时

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

NSURL 的资源路径转换为string 始终返回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

【问题讨论】:

  • 您的意思是将资源路径字符串转换为 NSURL 对吗?
  • 是的,我认为我需要获取一个字符串值? (第一次尝试mac应用程序开发,所以我可能错了)
  • 如果您显示您的 println() 语句的实际输出将会很有帮助。
  • 路径:Optional(file:///Users/*******/Library/Developer/Xcode/DerivedData/Electrical_Calculators-askhpxrxvlxbdxcfdbyosdczzquo/Build/Products/Debug/Electrical%20Calculators.app/Contents/Resources/myResource.html)
  • 如果你需要一个 url,你为什么要得到一个路径?

标签: macos swift webkit


【解决方案1】:
if let myFileUrl = NSBundle.mainBundle().URLForResource("yourFile", withExtension: "html"){
            // do whatever with your url
} 

【讨论】:

  • 感谢您的回答,加 1
【解决方案2】:

Leonardo 的答案中给出的代码应该可以工作,而且更简单、更安全 具有可选绑定的方法。这是一个解释为什么你的 代码失败:

let requesturl = NSURL(string: urlpath!)

返回nil,因为urlpath文件路径,而不是URL 字符串 (如“file:///path/to/file”)。

如果您将该行替换为

let requesturl = NSURL(fileURLWithPath: urlpath!)

然后您将获得预期的输出。

【讨论】:

  • 好的,但这给了我与urlPathOptional(file:///Users/*******/Library/Developer/Xcode/DerivedData/Electrical_Calcula‌​tors-askhpxrxvlxbdxcfdbyosdczzquo/Build/Products/Debug/Electrical%20Calculators.a‌​pp/Contents/Resources/myResource.html)相同的效果
  • 我认为问题是现在显示 html 文件,因为我现在正在加载它(有点),感谢您的解释
  • @JSA986:奇怪,我已经测试了你的确切代码,第一个 println 产生了输出resource path = Optional("/Users/.../Build/Products/Debug/Electrical Calculator.app/Contents/Resources/myResource.html"),没有file:///
【解决方案3】:

对于 Swift 5

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

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多