我正在尝试使用从我的Node JS服务器获取的数据创建内容提要。
这里我从我的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.title
和post.description
的文本已经正确,但是从Image()
没有任何显示。我该如何使用我的服务器URL来显示图片?
ImageView(withURL: "http://localhost:8000/\(post.path)")
- DDavis25AsyncImage
的更详细指南,请查看:https://dev59.com/S1IH5IYBdhLWcg3wL6hJ#67919836。 - Pranav Kasetti