Get data from XCAsset catalog

I understand that to get images from the asset catalog, I can use UIImage (named: "fileName") to do this.

however, what if I get DATA from the XCAsset directory? I can’t figure it out.

I tried,

let url = NSBundle.mainBundle().URLForResource("fileName", withExtension: nil) let data = NSData(contentsOfURL: url!) 

But this is zero. I do not know how to get data from the XCAssets directory. If anyone can help me (google search didn’t help), please let me know, I will be very grateful!

Update:

Why am I trying to get data from the asset catalog? I dragged the animated gif into the asset directory. And the asset catalog interprets this as DATA. This is why I am trying to get data from the asset catalog.

Update: This image on the screen of my Assets.xcassets folder looks like.

image It has a file called "_Loading", and on the right it is considered a "Data set". I'm not sure how to get the dataset from the Assets directory.

+7
ios swift xcasset asset-catalog
source share
2 answers

I am going to answer my own question.

Starting with iOS 9, the Asset Catalog allows you to use more than just images. They allow a dataset. To retrieve data from the Asset Catalog, you must use the NSDataAsset class.

Example: suppose you have a 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 the NSData object into json.

Link to the NSDataAsset Class

+38
source share

Download the gif image from the Assets.xcassets file. The same goes for downloading json files.

  • NEW: 【New dataset】 splits the dataset and renames it “funny” in the Assets.xcassets folder. everything is fine, the gif file is added to the Assets.xcassets folder. enter image description here

  • Using:

     NSDataAsset *asset = [[NSDataAsset alloc] initWithName:@"funny"]; self.gifImageView.image = [UIImage sd_animatedGIFWithData:asset.data]; 
    • (UIImage *) sd_animatedGIFWithData: (NSData *) data: this is the UIImage + GIF category for uploading a gif image to SDWebImage.
0
source share

All Articles