NetworkImage is a Swift package that provides image downloading, caching, and displaying for your SwiftUI apps. It leverages the foundation URLCache
and NSCache
, providing persistent and in-memory caches.
Explore the companion demo project to discover its capabilities.
You can use NetworkImage on the following platforms:
- macOS 11.0+
- iOS 14.0+
- tvOS 14.0+
- watchOS 7.0+
A network image downloads and displays an image from a given URL; the download is asynchronous, and the result is cached both in disk and memory.
The simplest way of creating a NetworkImage
view is to pass the image URL to the init(url:scale:)
initializer.
NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200"))
.frame(width: 300, height: 200)
To manipulate the loaded image, use the content
parameter.
NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { image in
image
.resizable()
.scaledToFill()
.blur(radius: 4)
}
.frame(width: 150, height: 150)
.clipped()
The view displays a standard placeholder that fills the available space until the image loads. You
can specify a custom placeholder by using the placeholder
parameter.
NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { image in
image
.resizable()
.scaledToFill()
} placeholder: {
ZStack {
Color.secondary.opacity(0.25)
Image(systemName: "photo.fill")
.imageScale(.large)
.blendMode(.overlay)
}
}
.frame(width: 150, height: 150)
.clipped()
To have more control over the image loading process, use the init(url:scale:transaction:content)
initializer, which takes a content
closure that receives a NetworkImageState
to indicate the state of the loading operation.
NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { state in
switch state {
case .empty:
ProgressView()
case .success(let image, let idealSize):
image
.resizable()
.scaledToFill()
case .failure:
Image(systemName: "photo.fill")
.imageScale(.large)
.blendMode(.overlay)
}
}
.frame(width: 150, height: 150)
.background(Color.secondary.opacity(0.25))
.clipped()
To use NetworkImage in a Swift Package Manager project, add the following line to the dependencies in your Package.swift
file:
.package(url: "https://github.com/gonzalezreal/NetworkImage", from: "6.0.0")
Include "NetworkImage"
as a dependency for your executable target:
.target(name: "<target>", dependencies: [
.product(name: "NetworkImage", package: "NetworkImage")
]),
Finally, add import NetworkImage
to your source code.
- From the File menu, select Add Packages…
- Enter
https://github.com/gonzalezreal/NetworkImage
into the Search or Enter Package URL search field - Link NetworkImage to your application target