(seen below) This code originally was implemented with a .json text file, but now I'm trying to change it to implement with a live url and I am not sure how to make it a global variable since once you switch to the url it has the URLSession task and you have to use task.resume() to make it keep updating but then i'm not sure how I would be able to return the decodable T to the catData array as a void function. Please help Thank you!
Start of my new implementation:
import UIKit
import SwiftUI
import CoreLocation
let catData: [Cat] = load("https://tmha-backend.herokuapp.com/api/cats/")
func load<T: Decodable>(_ linkname: String) -> T {
let url = URL(string: "https://tmha-backend.herokuapp.com/api/cats/")
guard let requestUrl = url else {fatalError("Couldn't find \(linkname)")}
var request = URLRequest(url: requestUrl)
// Specify HTTP Method to use
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
// Send HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
var returnValue: Cat?
let decoder = JSONDecoder()
returnValue = try decoder.decode(Cat.self, from: data)
} catch {
fatalError("Couldn't parse \(linkname) as \(T.self):\n\(error)")
}
}
task.resume()
}
original code:
import UIKit
import SwiftUI
import CoreLocation
let catData: [Cat] = load("catData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}