Get Data from XCAsset catalog Get Data from XCAsset catalog swift swift

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


Load gif image from Assets.xcassets file. That`s same for loading json files.

  1. NEW: 【New Data Set】 crate a data set and rename "funny" in Assets.xcassets folder. all right, the gif file is added to Assets.xcassets folder.enter image description here

  2. USE:

    NSDataAsset *asset = [[NSDataAsset alloc] initWithName:@"funny"]; self.gifImageView.image = [UIImage sd_animatedGIFWithData:asset.data];                                        
    • (UIImage *)sd_animatedGIFWithData:(NSData *)data: is a UIImage+GIF category for loading gif image in SDWebImage.