Got thrown a fatal error in the do catch block under let jsonDecoder ...
import SwiftUI
import Foundation
struct AllVar: Codable {
public var value1: String
public var value2: String
public var value3: String
}
func decode() -> AllVar? {
var myVar : AllVar?
var data : Data?
// SKIP THIS let data = jsonString.data(using: .utf8, allowLossyConversion: false) // Use directly the data you get from url
if let url = URL(string: "https://sheetsu.com/apis/v1.0su/4a6eb0e90aa4") { // urlString is the url
let urlSession = URLSession(configuration: .default).dataTask(with: url) { (readData, response, error) in
data = readData
}
urlSession.resume()
}
let jsonDecoder = JSONDecoder()
do {
myVar = try jsonDecoder.decode(AllVar.self, from: data!) //Fatal Error Thrown here → Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
return myVar
} catch {
//print("Decode error", jsonString)
}
return nil
}
struct ContentView: View {
var myVar = decode() //Line 40 Added Code
var body: some View {
VStack{
Text(myVar?.value1 ?? "")
Text(myVar?.value2 ?? "")
Text(myVar?.value3 ?? "")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: