How to Show an Image From a URL in SwiftUI

How to Show an Image From a URL in SwiftUI

Written by

in

Quick answer: SwiftUI’s Image(“…”) initialiser only looks up a name in the asset catalog or an SF Symbol — it never performs a network request, so a URL string silently renders nothing. Load the bytes yourself with AsyncImage (iOS 15+) or a URLSession-based loader, then wrap the result in Image(uiImage:).

Why this happens

Image("http://localhost:8000/" + post.path) looks correct but does nothing, because Image(_:) takes an asset name, not a URL. At render time SwiftUI asks the asset catalog for an image with that name, finds no match, and draws an empty view. No network request is made, so there is no error to catch and nothing appears in the console.

Your feed shows the titles and descriptions because those are plain strings. The image is the only part that needs bytes from the server, and SwiftUI will not fetch them for you.

The second half of the problem is the URL itself. String concatenation with + produces nil from URL(string:) as soon as a path contains a space or other character that must be percent-encoded. Even a working loader will fail silently against a malformed URL.

If your deployment target is iOS 15 or later, the built-in AsyncImage solves the whole thing in one line. Below that, or when you need caching and cancellation control, you write a small loader.

How to fix it

1. Use AsyncImage on iOS 15 and later

AsyncImage downloads the URL, decodes it, and redraws when the data arrives:

import SwiftUI

struct PostRow: View {
    let post: Post

    var body: some View {
        HStack {
            AsyncImage(url: imageURL) { image in
                image
                    .resizable()
                    .scaledToFill()
            } placeholder: {
                ProgressView()
            }
            .frame(width: 80, height: 80)
            .clipped()

            VStack(alignment: .leading) {
                Text(post.title)
                Text(post.description)
            }
        }
    }

    private var imageURL: URL? {
        URL(string: post.path, relativeTo: URL(string: "http://localhost:8000/"))
    }
}

Note the .resizable() call. Without it the decoded image renders at its intrinsic pixel size and can blow out the row layout — another reason people think “nothing loaded” when actually an oversized image pushed the text off screen.

When you need to distinguish loading from failure, use the phase-based initialiser:

AsyncImage(url: imageURL) { phase in
    switch phase {
    case .success(let image):
        image.resizable().scaledToFill()
    case .failure:
        Image(systemName: "photo.badge.exclamationmark")
            .foregroundStyle(.secondary)
    case .empty:
        ProgressView()
    @unknown default:
        EmptyView()
    }
}

2. Build the URL instead of concatenating strings

URL(string:relativeTo:) and appending(path:) escape the path segments for you, and they return an optional you are forced to handle:

let base = URL(string: "http://localhost:8000/")!
let imageURL = base.appending(path: post.path)   // iOS 16+
// or, for older targets:
let imageURL = base.appendingPathComponent(post.path)

If post.path already starts with a slash, appendingPathComponent handles it; plain + does not, and you end up with // in the address. Worth printing the resolved absoluteString once while debugging.

3. Write a cached loader when AsyncImage is not enough

AsyncImage has no in-memory cache you control, so every time a row scrolls back into view it can start another request and re-decode. NSCache plus a task you can cancel fixes both:

import SwiftUI
import UIKit

@MainActor
final class ImageLoader: ObservableObject {
    @Published private(set) var image: UIImage?

    private static let cache = NSCache<NSURL, UIImage>()
    private var task: Task<Void, Never>?

    func load(_ url: URL) {
        if let cached = Self.cache.object(forKey: url as NSURL) {
            image = cached
            return
        }
        task?.cancel()
        task = Task {
            do {
                let (data, _) = try await URLSession.shared.data(from: url)
                guard !Task.isCancelled, let decoded = UIImage(data: data) else { return }
                Self.cache.setObject(decoded, forKey: url as NSURL)
                image = decoded
            } catch {
                // Leave the placeholder in place on failure.
            }
        }
    }
}

struct CachedImage: View {
    let url: URL
    @StateObject private var loader = ImageLoader()

    var body: some View {
        Group {
            if let image = loader.image {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFill()
            } else {
                ProgressView()
            }
        }
        .frame(width: 80, height: 80)
        .clipped()
        .task(id: url) { loader.load(url) }
    }
}

.task(id:) runs when the view appears, restarts if url changes, and cancels on disappearance — which is what keeps a fast-scrolling list from queueing dozens of stale downloads.

4. Let the dev server speak HTTP

App Transport Security blocks cleartext http:// requests. HTTPS endpoints need nothing, but a local Node server over plain HTTP will fail inside the loader. For local development only, add this to Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

Keep production endpoints on HTTPS rather than widening the exception.

How to prevent it

  • Treat Image(_:) as an asset-catalog lookup only; any remote source needs a loader (AsyncImage or URLSession).
  • Never build request URLs with +; use appendingPathComponent or appending(path:) and handle the optional.
  • Always pair .resizable() with an explicit .frame(...) so a decoded image cannot distort the layout.
  • Handle .failure and the empty phase in every list row — a broken image URL is far more common than you expect.
  • Cache decoded UIImage objects in NSCache and cancel in-flight tasks when cells go off screen.

FAQ

Why does Image(“https://…”) show nothing at all?

Because Image(_:) resolves a name in the asset catalog or an SF Symbol. A URL string matches neither, so the view renders empty, with no console output and no thrown error.

Is there a way to do this before iOS 15?

Yes. Use URLSession.shared.dataTask(with:) or data(from:), decode the bytes with UIImage(data:), publish the result from your ObservableObject on the main actor, and render it with Image(uiImage:).

Does AsyncImage cache downloaded images?

It relies on the default URLSession cache behaviour for the network response; it does not expose an in-memory image cache you can clear or prefill. If repeated scrolling re-downloads or re-decodes, wrap the decode step in your own NSCache as shown above.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.