在SwiftUI中,有一些.init
方法可以创建一个图像,但是它们都不允许使用块或任何其他方式从网络/缓存中加载UIImage ...
我正在使用Kingfisher从网络中加载图像并在列表行中缓存,但是在视图中绘制图像的方法是再次重新呈现它,我不希望这样做。另外,在获取图像时,我正在创建一个假图像(仅彩色)作为占位符。 另一种方法是将所有内容包装在自定义视图中,然后仅重新渲染包装器。但是我还没有尝试过。
此示例现在正在运行。 任何改善当前想法的想法都会很棒
使用加载程序的某些视图
struct SampleView : View {
@ObjectBinding let imageLoader: ImageLoader
init(imageLoader: ImageLoader) {
self.imageLoader = imageLoader
}
var body: some View {
Image(uiImage: imageLoader.image(for: "https://url-for-image"))
.frame(width: 128, height: 128)
.aspectRatio(contentMode: ContentMode.fit)
}
}
import UIKit.UIImage
import SwiftUI
import Combine
import class Kingfisher.ImageDownloader
import struct Kingfisher.DownloadTask
import class Kingfisher.ImageCache
import class Kingfisher.KingfisherManager
class ImageLoader: BindableObject {
var didChange = PassthroughSubject<ImageLoader, Never>()
private let downloader: ImageDownloader
private let cache: ImageCache
private var image: UIImage? {
didSet {
dispatchqueue.async { [weak self] in
guard let self = self else { return }
self.didChange.send(self)
}
}
}
private var task: DownloadTask?
private let dispatchqueue: DispatchQueue
init(downloader: ImageDownloader = KingfisherManager.shared.downloader,
cache: ImageCache = KingfisherManager.shared.cache,
dispatchqueue: DispatchQueue = DispatchQueue.main) {
self.downloader = downloader
self.cache = cache
self.dispatchqueue = dispatchqueue
}
deinit {
task?.cancel()
}
func image(for url: URL?) -> UIImage {
guard let targetUrl = url else {
return UIImage.from(color: .gray)
}
guard let image = image else {
load(url: targetUrl)
return UIImage.from(color: .gray)
}
return image
}
private func load(url: URL) {
let key = url.absoluteString
if cache.isCached(forKey: key) {
cache.retrieveImage(forKey: key) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let value):
self.image = value.image
case .failure(let error):
print(error.localizedDescription)
}
}
} else {
downloader.downloadImage(with: url, options: nil, progressBlock: nil) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let value):
self.cache.storeToDisk(value.originalData, forKey: url.absoluteString)
self.image = value.image
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
}
答案 0 :(得分:4)
在SwiftUI中加载图像的更简单,更简洁的方法是使用著名的Kingfisher库。
Kingfisher
选择文件> Swift软件包>添加软件包依赖关系。输入 https://github.com/onevcat/Kingfisher.git
在“选择软件包”中 “存储库”对话框。在下一页中,指定要解析的版本 最早的版本是“ 5.8.0”作为“ Up Up Next Major”规则。
之后 Xcode签出源代码并解析版本,您可以 选择“ KingfisherSwiftUI”库并将其添加到您的应用目标中。
import KingfisherSwiftUI
KFImage(myUrl)
完成!就是这么简单
答案 1 :(得分:3)
从 iOS 15 开始,我们现在可以使用 AsyncImage
:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in
image.resizable()
} placeholder: {
ProgressView()
}
.frame(width: 50, height: 50)
这是一个支持缓存和多种加载状态的原生 SwiftUI 解决方案:
import Combine
import SwiftUI
struct NetworkImage: View {
@StateObject private var viewModel = ViewModel()
let url: URL?
var body: some View {
Group {
if let data = viewModel.imageData, let uiImage = UIImage(data: data) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fit)
} else if viewModel.isLoading {
ProgressView()
} else {
Image(systemName: "photo")
}
}
.onAppear {
viewModel.loadImage(from: url)
}
}
}
extension NetworkImage {
class ViewModel: ObservableObject {
@Published var imageData: Data?
@Published var isLoading = false
private static let cache = NSCache<NSURL, NSData>()
private var cancellables = Set<AnyCancellable>()
func loadImage(from url: URL?) {
isLoading = true
guard let url = url else {
isLoading = false
return
}
if let data = Self.cache.object(forKey: url as NSURL) {
imageData = data as Data
isLoading = false
return
}
URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.replaceError(with: nil)
.receive(on: DispatchQueue.main)
.sink { [weak self] in
if let data = $0 {
Self.cache.setObject(data as NSData, forKey: url as NSURL)
self?.imageData = data
}
self?.isLoading = false
}
.store(in: &cancellables)
}
}
}
(上面的代码没有使用任何第三方库,所以很容易以任何方式改变NetworkImage
。)
演示
import Combine
import SwiftUI
struct ContentView: View {
@State private var showImage = false
var body: some View {
if showImage {
NetworkImage(url: URL(string: "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png"))
.frame(maxHeight: 150)
.padding()
} else {
Button("Load") {
showImage = true
}
}
}
}
(我使用了一个特别大的 Stack Overflow 标志来显示加载状态。)
答案 2 :(得分:2)
我只会使用onAppear
回调
import Foundation
import SwiftUI
import Combine
import UIKit
struct ImagePreviewModel {
var urlString : String
var width : CGFloat = 100.0
var height : CGFloat = 100.0
}
struct ImagePreview: View {
let viewModel: ImagePreviewModel
@State var initialImage = UIImage()
var body: some View {
Image(uiImage: initialImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: self.width, height: self.height)
.onAppear {
guard let url = URL(string: self.viewModel.urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
RunLoop.main.perform {
self.initialImage = image
}
}.resume()
}
}
var width: CGFloat { return max(viewModel.width, 100.0) }
var height: CGFloat { return max(viewModel.height, 100.0) }
}
答案 3 :(得分:1)
将 assert new File("./resources/Menu_de_itens.txt").canRead();
定义为@ObjectBinding
:
imageLoader
使用图片的网址初始化视图会更有意义:
@ObjectBinding private var imageLoader: ImageLoader
例如:
struct SampleView : View {
var imageUrl: URL
private var image: UIImage {
imageLoader.image(for: imageUrl)
}
@ObjectBinding private var imageLoader: ImageLoader
init(url: URL) {
self.imageUrl = url
self.imageLoader = ImageLoader()
}
var body: some View {
Image(uiImage: image)
.frame(width: 200, height: 300)
.aspectRatio(contentMode: ContentMode.fit)
}
}
答案 4 :(得分:0)
将模型传递到包含URL的ImageRow结构。
import SwiftUI
import Combine
struct ContentView : View {
var listData: Post
var body: some View {
List(model.post) { post in
ImageRow(model: post) // Get image
}
}
}
/********************************************************************/
// Download Image
struct ImageRow: View {
let model: Post
var body: some View {
VStack(alignment: .center) {
ImageViewContainer(imageUrl: model.avatar_url)
}
}
}
struct ImageViewContainer: View {
@ObjectBinding var remoteImageURL: RemoteImageURL
init(imageUrl: String) {
remoteImageURL = RemoteImageURL(imageURL: imageUrl)
}
var body: some View {
Image(uiImage: UIImage(data: remoteImageURL.data) ?? UIImage())
.resizable()
.clipShape(Circle())
.overlay(Circle().stroke(Color.black, lineWidth: 3.0))
.frame(width: 70.0, height: 70.0)
}
}
class RemoteImageURL: BindableObject {
var didChange = PassthroughSubject<Data, Never>()
var data = Data() {
didSet {
didChange.send(data)
}
}
init(imageURL: String) {
guard let url = URL(string: imageURL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
DispatchQueue.main.async { self.data = data }
}.resume()
}
}
/********************************************************************/
答案 5 :(得分:0)
import SwiftUI
struct UrlImageView: View {
@ObservedObject var urlImageModel: UrlImageModel
init(urlString: String?) {
urlImageModel = UrlImageModel(urlString: urlString)
}
var body: some View {
Image(uiImage: urlImageModel.image ?? UrlImageView.defaultImage!)
.resizable()
.scaledToFill()
}
static var defaultImage = UIImage(systemName: "photo")
}
class UrlImageModel: ObservableObject {
@Published var image: UIImage?
var urlString: String?
init(urlString: String?) {
self.urlString = urlString
loadImage()
}
func loadImage() {
loadImageFromUrl()
}
func loadImageFromUrl() {
guard let urlString = urlString else {
return
}
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url, completionHandler:
getImageFromResponse(data:response:error:))
task.resume()
}
func getImageFromResponse(data: Data?, response: URLResponse?, error: Error?)
{
guard error == nil else {
print("Error: \(error!)")
return
}
guard let data = data else {
print("No data found")
return
}
DispatchQueue.main.async {
guard let loadedImage = UIImage(data: data) else {
return
}
self.image = loadedImage
}
}
}
并像这样使用:
UrlImageView(urlString: "https://developer.apple.com/assets/elements/icons/swiftui/swiftui-96x96_2x.png").frame(width:100, height:100)
答案 6 :(得分:0)
随着 2021 年 iOS 15 和 macOS 12 的发布,SwiftUI 提供了原生 AsyncImage
视图,可以异步加载图像。请记住,对于较早的操作系统版本,您仍然需要使用自定义实现。
AsyncImage(url: URL(string: "https://example.com/tile.png"))
API 本身还提供了多种方式来自定义图像或提供占位符,例如:
AsyncImage(url: URL(string: "https://example.com/tile.png")) { image in
image.resizable(resizingMode: .tile)
} placeholder: {
Color.green
}