【问题标题】:Get resource URL from project specific path从项目特定路径获取资源 URL
【发布时间】:2016-02-09 01:07:43
【问题描述】:

我需要通过从项目目录(又名 mainBundle)开始的路径检索包含在我的 Xcode 项目中的资源的 URL

所以如果我指定的路径是 ./snd/archer/acknowledge1.wav,我需要从中创建一个 URL。

我知道我可以将NSURL(fileURLWithPath:) 用于系统目录,但我不知道如何直接从捆绑包中执行此操作。

【问题讨论】:

    标签: swift nsurl nsfilemanager nsbundle


    【解决方案1】:

    从 Swift 3 开始,答案是:

    Bundle.main.url(forResource: "acknowledge1", withExtension: "wav", subdirectory: "snd/archer")
    

    【讨论】:

    • 请修正您的答案。在“子目录”之前需要逗号。这是 Swift 4(也许是 Swift 3)的绝佳答案
    • 在 Swift 4 中,我只需要提供 forResource 和 withExtension。当我提供子目录时,它没有找到我正在加载的 .webarchive(它位于子目录中)。
    【解决方案2】:

    您将使用其中一种捆绑资源 URL 方法

    [[NSBundle mainBundle] URLForResource:@"acknowledge1"
                            withExtension:@"wav"
                             subdirectory:@"snd/archer"];
    
    NSBundle.mainBundle().URLForResource("acknowledge1", withExtension:"wav" subdirectory:"snd/archer")
    

    在最新的 Swift 中:

    Bundle.main.url(forResource: "acknowledge1", withExtension:"wav")
    

    【讨论】:

    • 最新的 swift 是什么?
    【解决方案3】:

    在 Swift 2.3 中,您必须使用这种展开:

    if let resourceUrl = NSBundle.mainBundle().URLForResource("acknowledge1", withExtension: "wav", subdirectory:"snd/archer") {
            if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
                print("file found")
                //do stuff
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      相关资源
      最近更新 更多