This is Model for My API and we will use this model in future. can Anyone tell me this is correct or Not. Im a native user of SwiftUI.
public struct Temperatures {
public let bookDetails: BookDetails
public init(bookDetails: BookDetails) {
self.bookDetails = bookDetails
}
}
public struct BookDetails {
public let data: [Datum]
public init(data: [Datum]) {
self.data = data
}
}
public struct Datum : Hashable, Identifiable {
public let id = UUID()
public let title: String
public let published: String
public let url: String
public init( title: String, published: String, url: String) {
self.title = title
self.published = published
self.url = url
}
}
And this is ViewModel And i cant fetch the data of data[]
View Model For Prime Book And Showing Details
class PrimeBookVM: ObservableObject{
@Published var datas = [Datum]()
init(){
let source = "https://********/api/book-search?is_prime"
let url = URL(string: source)!
let session = URLSession(configuration: .default)
session.dataTask(with: url){
(data, _, err) in
if err != nil{
print(err?.localizedDescription ?? "Hello Error")
return
}
let json = try!JSON(data: data!)
for i in json["data"]{
let published = i.1["published"].stringValue
let title = i.1["title"].stringValue
let url = i.1["url"].stringValue
DispatchQueue.main.async {
self.datas.append(Datum(title: title, published: published, url: url))
}
}
}
.resume()
}
}
This is my View and try to fetch the detail of data array in api.
struct PrimeBooksView: View{
@StateObject var list = PrimeBookVM()
var body: some View{
ScrollView(.horizontal){
HStack{
ForEach(list.datas, id: \.self){ item in
VStack(alignment: .leading){
WebImage(url: URL(string: item.url)!, options: .highPriority, context: nil)
.resizable()
.frame(width: 180, height: 230)
Text(item.title)
.multilineTextAlignment(.leading)
.font(.system(size: 16))
.foregroundColor(Color("default"))
Text(item.published)
.font(.system(size: 12))
.fontWeight(.light)
.foregroundColor(Color("default"))
}
.padding(.all,4)
.background(Color.white).cornerRadius(8)
.shadow(color: .gray, radius: 1)
}
.padding(.all,1)
}
}
}
}
Thank You So much in Advance for Help.
SwiftyJSON. It's not topical anymore. Decode the JSON directly into the model withJSONDecoder. And please have a close look at the JSON. The keydatais insideBookDetailswhich is not the root object. By the way.padding(.all,4)and.padding(4)does the same.