一个替代 SwiftUI 的 AsyncImage
的直接替代品,支持自定义 URLSessions、缓存和动画阶段变化。
通过 Swift Package Manager 将 RemoteImage
添加到您的项目中,并在您想使用它的地方添加 import RemoteImage
。
.package(url: "https://github.com/bdbergeron/RemoteImage", from: "1.0.0"),
RemoteImage
的 API 经过精心设计,使其在您的应用/项目中非常容易采用。在大多数情况下,它是一个简单的 SwiftUI AsyncImage
的直接替代品。
在 Xcode 项目中查看 RemoteImage Demos
应用,以查看一些实时示例。
let imageURL: URL?
/// A simple `RemoteImage` view.
RemoteImage(url: imageURL)
/// A simple `RemoteImage` view with modifier closure.
RemoteImage(url: imageURL) {
$0.resizable().scaledToFit()
}
/// A `RemoteImage` view with a custom placeholder view.
RemoteImage(url: imageURL) {
$0.resizable().scaledToFit()
} placeholder: {
ProgressView()
}
/// A `RemoteImage` view with custom placeholder and failure views.
RemoteImage(url: imageURL) {
$0.resizable().scaledToFit()
} placeholder: {
ProgressView()
} failure: { error in
ZStack {
Color.yellow.opacity(0.3)
Text("Image could not be loaded.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
let imageURL: URL?
let urlSession = URLSession(configuration: .ephemeral)
let imageCache = URLCache(memoryCapacity: 10_000_000, diskCapacity: 0)
/// Image loaded with a custom `URLSession` and using a custom phase transition animation.
RemoteImage(
url: imageURL,
urlSession: urlSession,
configuration: RemoteImageConfiguration(
transaction: Transaction(
animation: .spring(duration: 1.0).delay(0.5))))
{
$0.resizable().scaledToFit()
}
/// Image loaded from a custom cache. If the image is not yet cached, a new `URLSession`
/// will be constructed using the `URLSessionConfiguration.default` configuration
/// and the provided cache instance.
RemoteImage(url: imageURL, cache: imageCache) {
$0.resizable().scaledToFit()
} placeholder: {
ZStack {
Color.black.opacity(0.05)
ProgressView()
}
}