iOS download and save image inside app
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Downloading an image and saving it inside an iOS app usually means two separate tasks: fetch the bytes from the network, then write those bytes to a file in your app's sandbox. Once the file is saved, you can load it again later without re-downloading it.
The most important design choice is where to store the image. Use the Caches directory for data you can redownload, and Documents only for files that are user-created or must be backed up.
Download the Image with URLSession
In modern Swift, async and await make this straightforward:
The UIImage(data:) check is important. A successful HTTP response does not guarantee the payload is actually an image.
Save the Downloaded Bytes to the App Sandbox
Here is a reusable save function that writes the file into Caches:
Then combine both steps:
That is enough for many apps.
Load the Saved Image Later
Once the file exists in your sandbox, you can recreate a UIImage from disk:
This lets you show the saved image on future launches without another network request.
Choose the Right Directory
This part matters more than many tutorials admit:
- '
Cachesis for redownloadable files such as remote avatars or thumbnails' - '
Documentsis for user-generated or must-keep files' - '
tmpis for short-lived scratch data'
If the image came from your server and can be fetched again, Caches is usually the correct destination. iOS may clear caches when space is tight, which is fine for data you can rebuild.
Saving to the Photos library is a different workflow entirely and requires separate user permission handling.
Think About File Names and Replacement
If you always save to the same file name, each download replaces the previous image. That may be exactly what you want for a user avatar, but not for a gallery or offline feed. A simple pattern is to derive the file name from a stable ID or a hash of the source URL.
Common Pitfalls
- Writing everything into
Documentswhen the files are really just cache data. - Updating UIKit views from background work without hopping back to the main actor where needed.
- Assuming a
200response always contains a valid image payload. - Forgetting file-name collisions and overwriting old images unintentionally.
- Loading huge image files into memory repeatedly instead of using caching or resized variants.
Summary
- Download the image bytes with
URLSession. - Validate that the payload really represents an image.
- Save the data into the app sandbox with
FileManager. - Prefer the
Cachesdirectory for redownloadable remote images. - Treat Photos-library saving as a separate permission-based feature, not the same as storing a file inside the app.

