如何在 SwiftUI 中显示来自 url 的图像 [英] How to display Image from a url in SwiftUI

查看:50
本文介绍了如何在 SwiftUI 中显示来自 url 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试使用从我的 Node JS 服务器获取的数据创建一个内容提要.

So I'm trying to create a content feed using data fetched from my Node JS server.

这里我从我的 API 中获取数据

class Webservice {
    func getAllPosts(completion: @escaping ([Post]) -> ()) {
        guard let url = URL(string: "http://localhost:8000/albums")
     else {
     fatalError("URL is not correct!")
    }

        URLSession.shared.dataTask(with: url) { data, _, _ in

            let posts = try!

                JSONDecoder().decode([Post].self, from: data!); DispatchQueue.main.async {
                    completion(posts)
            }
        }.resume()
    }
}

将变量设置为从 API 获取的数据

final class PostListViewModel: ObservableObject {

    init() {
        fetchPosts()
    }

    @Published var posts = [Post]()

    private func fetchPosts() {
        Webservice().getAllPosts {
            self.posts = $0
        }
    }


}

struct Post: Codable, Hashable, Identifiable {

    let id: String
    let title: String
    let path: String
    let description: String
}

SwiftUI

struct ContentView: View {

    @ObservedObject var model = PostListViewModel()

        var body: some View {
            List(model.posts) { post in
                HStack {
                Text(post.title)
                Image("http://localhost:8000/" + post.path)
                Text(post.description)

                }

            }
        }

}

post.titlepost.description 中的文本显示正确,但 Image() 没有显示任何内容.如何使用来自我的服务器的 URL 与我的图像一起显示?

The Text from post.title and post.description are display correctly but nothing displays from Image(). How can I use a URL from my server to display with my image?

推荐答案

iOS 15 更新:

您可以通过以下方式使用 asyncImage:

iOS 15 update:

you can use asyncImage in this way:

AsyncImage(url: URL(string: "https://your_image_url_address"))

有关 Apple 开发者文档的更多信息:AsyncImage

more info on Apple developers document: AsyncImage

首先你需要从 url 获取图片:

first you need to fetch image from url :

class ImageLoader: ObservableObject {
    var didChange = PassthroughSubject<Data, Never>()
    var data = Data() {
        didSet {
            didChange.send(data)
        }
    }

    init(urlString:String) {
        guard let url = URL(string: urlString) else { return }
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            DispatchQueue.main.async {
                self.data = data
            }
        }
        task.resume()
    }
}

你也可以把它作为你的 Webservice 类函数的一部分.

you can put this as a part of your Webservice class function too.

然后在您的 ContentView 结构中,您可以通过这种方式设置 @State 图像:

then in your ContentView struct you can set @State image in this way :

struct ImageView: View {
    @ObservedObject var imageLoader:ImageLoader
    @State var image:UIImage = UIImage()

    init(withURL url:String) {
        imageLoader = ImageLoader(urlString:url)
    }

    var body: some View {
        
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width:100, height:100)
                .onReceive(imageLoader.didChange) { data in
                self.image = UIImage(data: data) ?? UIImage()
        }
    }
}

此外,这个教程<如果您需要更多,/a> 是一个很好的参考

Also, this tutorial is a good reference if you need more

这篇关于如何在 SwiftUI 中显示来自 url 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆