Hi, I am able to get data in an array and loop through it but how can I get single object data and display it?
artwork view
import SwiftUI
struct ArtworkView: View {
@StateObject var singleArtwork = SingleArtwork()
var body: some View {
NavigationView {
List {
ForEach(singleArtwork.artworksData, id: \.self) { artwork in
HStack(spacing: 8) {
URLImage(urlString: "https://melvynbiddulph.co.uk/images/gallery/"+artwork.file)
Text(artwork.title)
.bold()
if (artwork.size != nil) {
Text(artwork.size)
}
}
}
}
.navigationTitle("Single Artwork")
.onAppear {
singleArtwork.fetch()
}
}
}
}
struct ArtworkView_Previews: PreviewProvider {
static var previews: some View {
ArtworkView()
}
}
Single Artwork Object
import SwiftUI
class SingleArtwork: ObservableObject {
@Published var artworksData: [Artwork] = []
func fetch() {
guard let url = URL(string: "https://melvynbiddulph.co.uk/api/artwork/11") else {
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
return
}
//convert to JSON
do {
let artworksData = try JSONDecoder().decode([Artwork].self, from: data)
DispatchQueue.main.async {
self.artworksData = artworksData
}
} catch {
print(error)
}
}
task.resume()
}
}
URLImage
import SwiftUI
struct URLImage: View {
let urlString: String
@State var data: Data?
var body: some View {
if let data = data, let uiimage = UIImage(data: data) {
Image(uiImage: uiimage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 130, height: 130)
.background(Color.gray)
} else {
Image(systemName: "loading")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 130, height: 130)
.background(Color.gray)
.onAppear {
fetchData()
}
}
}
private func fetchData() {
guard let url = URL(string: urlString) else {
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
self.data = data
}
task.resume()
}
}
Obviously it works for an array of objects: https://www. melvynbiddulph .co.uk/api/artwork
but not working for single objects: https://www. melvynbiddulph .co.uk/api/artwork/11