简体   繁体   English

无法从Xcode 7中的资产目录中检索非jpg / png文件

[英]Can't retrieve non jpg/png files from the Asset Catalog in Xcode 7

I want retrieve non jpg/png files from the Asset Catalog in Xcode 7. I saw it was possible now to add any kind of data into to Asset Catalog. 我想从Xcode 7中的资产目录中检索非jpg / png文件。我看到现在可以将任何类型的数据添加到资产目录中。

So the way I was doing it was working before moving gif/video from Xcode project into the Assets Catalog 所以我在做这件事的方式是在将GIF /视频从Xcode项目移动到资产目录之前

private struct WalkthroughVideo {
    static let name = "tokyo"
    static let type = "mp4"
  }

private var moviePlayer : AVPlayerViewController? = {
    guard let path = NSBundle.mainBundle().pathForResource(WalkthroughVideo.name, ofType: WalkthroughVideo.type) else {
      return nil
    }
    let url = NSURL.fileURLWithPath(path)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = AVPlayer(URL: url)
    return playerViewController
   }()

So now path is nil. 所以现在路径是零。 It can't find the file. 它无法找到该文件。 Is there a new way to retrieve dataset ? 有没有新的方法来检索数据集?

Obviously pathForResource is not going to work, because the resource is not in your app bundle any more - it's in your asset catalog. 显然, pathForResource不起作用,因为资源不再在你的应用程序包中 - 它在你的资产目录中。 In effect, it no longer has any "path". 实际上,它不再有任何“路径”。

You have to use the new NSDataAsset class, which can fetch arbitrary data by name out of the asset catalog. 您必须使用新的NSDataAsset类,该类可以按名称从资产目录中获取任意数据。 To simulate your tokyo.mp4 example, I used an AIFF sound file, stored in my asset catalog as a data set called theme (in the Universal slot). 为了模拟你的tokyo.mp4例子,我使用了一个AIFF声音文件,存储在我的资产目录中,作为一个名为theme的数据集(在Universal插槽中)。 Here's my complete test code (in my root view controller): 这是我的完整测试代码(在我的根视图控制器中):

var player : AVAudioPlayer!
override func viewDidLoad() {
    super.viewDidLoad()
    if let asset = NSDataAsset(name: "theme") {
        let data = asset.data
        self.player = try! AVAudioPlayer(data:data)
        self.player.play()
    }
}

Lo and behold, the sound played! 瞧,声音播放了! Of course in real life I would have added error handling on that try . 当然在现实生活中,我会在try添加错误处理。

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

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