How to Get a Nsurl from an Xcassets Bundle

Can I get a NSURL from an XCAssets bundle?

If you're targeting iOS 7+, Xcode 5 now puts the assets into a new file format. 1 file for all of the assets. This means you can not get access to the file directly.

If you need to access the file directly, you can include it as an normal image outside of an asset catalog.

Access Asset Catalog pathForResource

Same problem, but I don't think we could access it via pathForResource:, except below:

UIImage* image = [UIImage imageNamed:@"name-in-asset-catalog"];

It has been clearly documented:

Each set in an asset catalog has a name. You can use that name to
programmatically load any individual image contained in the set. To
load an image, call the UIImage:imageNamed: method, passing the name
of the set that contains the image.

I found that in the package of complied app, a file named "Assets.car" came out, and I think it's the entire images sets in my project, and should have been zipped or something.

Refer to Apple's documentation:

Xcode 5 provides different functionality for asset catalogs depending
on the deployment target for your project:

  • For all projects, individual images can be loaded using set names.
  • For projects with a deployment target of iOS 7, Xcode compiles your asset
    catalogs into a runtime binary file format that reduces the download
    time for your app.

So that's it.

I'm also looking for a way that doesn't use imageNamed:, I don't want runtime to cache my images.

Get Data from XCAsset catalog

I am going to answer my own question.

Since iOS 9, the Asset Catalog allows more than just Images. They allow Data sets. In order to get data from the Asset Catalog, you must use the NSDataAsset class.

Example: Assume you have an Data Asset named "CoolJSON"

if let asset = NSDataAsset(name: "CoolJSON") {
let data = asset.data
let d = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
}

In this example I turned an NSData object into a json.

NSDataAsset class reference

Impossible to load an image in xcassets on bundle

There are two ways to solve this,

If your app is still supporting iOs 7, you can use this category:
https://gist.github.com/serluca/e4f6a47ffbc19fccc63e

Otherwise, starting from iOs 8 Apple added a way to do this using:
+ imageNamed:inBundle:compatibleWithTraitCollection: defined here



Related Topics



Leave a reply



Submit