Read image from asset catalog

I drag a image.jpg into the assets.xcassets. And I want to read the jpg data in my code by

"var imageData = NSDataAsset(name: "image")?.data"

However, I get an error: "CoreUI: attempting to lookup a named data 'image' with a type that is not a data type in the AssetCatalog". And "imageData" is always nil.

Do I make a mistake or miss sth? Thanks in advance.
Answered by OOPer in 671825022

I drag a image.jpg into the assets.xcassets.

Then you have added an Image Set of name image to the Asset catalogue, not Data Set.

You may need to use UIImage.init(named:).
Or else if you want to use NSDataAsset, you need to add a Data Set.
Accepted Answer

I drag a image.jpg into the assets.xcassets.

Then you have added an Image Set of name image to the Asset catalogue, not Data Set.

You may need to use UIImage.init(named:).
Or else if you want to use NSDataAsset, you need to add a Data Set.

I drag a image.jpg into the assets.xcassets.

Then you have added an Image Set of name image to the Asset catalogue, not Data Set.
You may need to use UIImage.init(named:).
Or else if you want to use NSDataAsset, you need to add a Data Set

It works for me. I make a new data set, and drag the image into it. Thanks a lot. The only flaw is that it would not to provide "1x、2x、3x" options for resources like image set. :(

BTW, is "UIImage(named:)" the only way to retrieve image data from image set in assets catalog? Are there other feasible methods, like by url, Data-like object, or ...? UIImage is a bit expensive for sizing and to resizing.

is "UIImage(named:)" the only way to retrieve image data from image set in assets catalog? 

As far as I know, YES.

UIImage is a bit expensive for sizing and to resizing. 

What are you trying to do? Does it make a significant difference between UIImage and Data of the image?
I'm writing a little app which will present some HD images. I need to keep the memory from spiking up. I fall back on ImageIO which needs images' data or url as input parameters.

If choose "url", I have not yet found a way to get urls of images in assets catalog. I don't want to put images in main bundle directly either. Therefore, it seems like I have to choose to retrieve images' data.

I try to use UIImage.jpegData(compressionQuality: ) and NSDataSet.data both. Final result is NSDataSet could save 10mb memory per image than UIImage.
Thanks for the explanation.
I'm not sure if your way is optimized for UIImage, but 10mb seems to be a significant difference. Hope you can find the best way.
Read image from asset catalog
 
 
Q