Reputation: 25
I'm using this API http://shibe.online/api/shibes? although when i load it, all i see is a single link which is what i want to use but there is no variable identifier associated with it.
["https://cdn.shibe.online/shibes/be12be31e2c880b4ac6992b3bb02751211b6ee68.jpg"]
import Foundation
import SwiftUI
import Combine
import SDWebImageSwiftUI
struct ShibeView: View {
@ObservedObject var fetcher = ShibeFetcher()
var body: some View {
AnimatedImage(url: URL(string: self.fetcher.shibe?.url ?? "")).resizable().scaledToFit()
}
}
public class ShibeFetcher: ObservableObject {
@Published var shibe: ShibeRecievers?
init(){
load()
}
func load() {
let url = URL(string: "http://shibe.online/api/shibes?")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
let webData = try JSONDecoder().decode(ShibeRecievers.self, from: d)
DispatchQueue.main.async {
self.shibe = webData
}
}else {
print("No Data")
}
} catch {
print ("Error here")
}
}.resume()
}
}
struct ShibeRecievers: Codable {
var url: String //Not sure how to store the link from the api
}
The problem i have is storing the link from the api into my app and I can't find any json parsing documentation without variable names.
Upvotes: 1
Views: 103
Reputation: 1274
Your json response is just an array of String. So you can decode it like this:
try! JSONDecoder().decode([String].self, from: d)
Completed version based on your current implementation:
struct ShibeView: View {
@ObservedObject var fetcher = ShibeFetcher()
var body: some View {
Image(uiImage: UIImage(data: try! Data(contentsOf: URL(string: fetcher.shibe?.first ?? "https://i.imgur.com/epMSRQH.png")!)) ?? UIImage())
}
}
public class ShibeFetcher: ObservableObject {
@Published var shibe: [String]?
init(){
load()
}
func load() {
let url = URL(string: "http://shibe.online/api/shibes?")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
let webData = try JSONDecoder().decode([String].self, from: d)
DispatchQueue.main.async {
self.shibe = webData
}
}else {
print("No Data")
}
} catch {
print ("Error here")
}
}.resume()
}
}
Upvotes: 1