I am getting an error which seems to be more of that the request did not go through correctly. I say that because when I reload the app it works fine
The part of the code causing the error is:
let post = try! JSONDecoder().decode(Post.self, from: data!)
the error is:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
the full code:
func getShows(station:String,completion: @escaping ([Program]) -> ()) {
guard let url = URL(string: "https://api.drn1.com.au/api-access/programs/(station)") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
// Based on the updated structs, you would no
// longer be decoding an array
let post = try! JSONDecoder().decode(Post.self, from: data!)
DispatchQueue.main.async{
// The array is stored under programs now
completion(post.programs)
}
}
.resume()
}
Is there away instead of crashing the app, it just tries to run again?
2
Answers
(Answering your question in the last sentence)
Yes, don’t force-unwrap "data", don’t force-resolve the "try". Doing either will result in a crash if either data is null (which, for network calls is a reasonable expectation), or if the JSONDecoder cannot parse the data correctly.
How often you call this method is up to you (e.g., as soon as a view is loaded).
`
If your app is for iOS 13+, and you can use
Combine
, then your method could be rewritten like this