2

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.

So the way I was doing it was working before moving gif/video from Xcode project into the Assets Catalog

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 ?

Aymenworks
  • 423
  • 7
  • 21

1 Answers1

4

Obviously pathForResource is not going to work, because the resource is not in your app bundle any more - it's in your asset catalog. 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. 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). 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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I think too I misunderstood this feature. I though it was not only for the on-demand resources ^^. But with on demand resources, it download ressources directly stored on the App Store, so when developing, we can't use this feature, isn't it ? – Aymenworks Jun 14 '15 at 17:26
  • I watched the What's new on Xcode 7 ( when he talks about on-demands ressources, tags ). I just saw there was a On demand ressources video. I'll check it. – Aymenworks Jun 14 '15 at 17:41
  • 1
    Okay, well I was totally wrong about that. Mark me down. But I've corrected my answer! Mark me back up again. I apologize, but we are all learning together... – matt Jun 17 '15 at 02:51
  • Nice, well, where did you find it ? And do you know if it's possible to do it directly from the storyboard ( for example for UIImage ) – Aymenworks Jun 17 '15 at 13:25
  • `NSDataAsset` is available only in iOS 9. Is it possible to access data asset files in iOS 8? – Franklin Yu Apr 12 '16 at 21:03