Search code examples
iosobjective-cxcodeassetscatalog

Downloading an image from URL with Asset Catalog perks


I am a newbie on iOS development and am developing my first serious app (Objective C).

I am using an external API and have gotten to a point where I need to download an image from said API to keep offline as cache.

Now, if I understood correctly I can add images to my app on XCode using the asset catalog. For example, if I add an image with [email protected], [email protected] and [email protected] versions, in order to use them later I only need to provide the "image" part to iOS and it will automatically return the version appropriate for the currently used device.

I cannot however add images to the asset catalog on runtime - I must create an NSData from the image URL and save it to the Documents folder.

The thing is, this API gives me a bunch of URL's for different versions of the image I need to download and among them are the @2X, @3X etc versions of the image, so I need to download all versions and use the asset catalog feature of retrieving the appropriate one for the device.

How can I achieve this?

Thank you very much in advance for your help and please correct me if I got something wrong.


Solution

  • so I need to download all versions and use the asset catalog feature of retrieving the appropriate one for the device.

    You don't need to. We add 2x and 3x images to our asset catalog because we don't know on what device our app is running. But in your case, you need to know this at runtime, so you already know what's the device.

    To get the scale factor for your device you can do:

    UIScreen.mainScreen().scale
    

    So, for 2x this will return 2 and for 3x it will return 3.

    From this, you can know what's the proper image you need to download from your API instead of downloading them all which would add unneeded overhead.