I am using Swift to get a JSON from a Coronavirus API. However when I try to run the code I get this error.
Fatal error: Unexpectedly found nil while unwrapping an Optional value: line 22
My part of my code is
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22}"
getData(from: url)
// Do any additional setup after loading the view.
}
private func getData(from url: String) {
let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
guard let data = data, error == nil else{
print("Something Went Wrong")
return
}
//Have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch{
print("failed to convert \(error.localizedDescription)")
}
guard let json = result else {
return
}
print(json.data.date)
})
getfromurl.resume()
}
Line 22 is:
let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
I am confused because I think that it means that url
has nothing assigned to it, but even the debugger thinks it does.
UPDATE:
I can get the data but I get an error once I get it. The error is:
failed to convert valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "newDeathsByDeathDate", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))
The failed to convert shows it is an error in decoding the JSON and the values.