获取资源的URL

问题描述:

我需要检索通过在项目目录(又名mainBundle)获取资源的URL

所以开始的路径包含在我的Xcode项目资源的URL,如果,如果我./snd指定路径/archer/acknowledge1.wav,我需要从中创建一个URL。

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

你会使用束国土资源URL方法

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

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

在最新一期斯威夫特:

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

随着斯威夫特3,得到的答案是:

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

请修复您的答案。 '子目录'之前需要逗号。这对于Swift 4(也许Swift 3)来说是个很好的答案, –

Swift 2.3 y你不得不使用这个解开:

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