I have this error while trying to get JSON file.
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Volumes/Data/Models.swift, line 40
Line 40 in my code below:
static func fetchFeaturedSearch(_ completionHandler: @escaping (FeaturedSearch) -> ()) {
When I copy the JSON data and put it in static file location, it works like a charm. But when trying to read the json data from the search service I have the error.
Nevertheless the data looks exactly the same!!
Please help me with this.
Server json file: ( causes the error )
https://nabulsiapps.com/articles-flutter/search/?lang=en&search=god&platform=ios
Same file on static JSON file: ( Works )
Here is the main code:
struct FeaturedSearch: Decodable {
var TotalNo: SearchCategory?
var categories: [SearchCategory]?
}
struct SearchCategory: Decodable {
let categoryName: String?
let categoryIcon: String?
let categoryId: Int?
let count: Int?
let articles: [articlesList]?
static func fetchFeaturedSearch(_ completionHandler: @escaping (FeaturedSearch) -> ()) {
let urlString = "https://nabulsiapps.com/articles-flutter/search/?lang=en&search=god&platform=ios"
//print(urlString)
URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
guard let data = data else { return }
if let error = error {
print(error)
return
}
do {
let decoder = JSONDecoder()
let featuredSearch = try decoder.decode(FeaturedSearch.self, from: data)
//print(featuredSearch)
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(featuredSearch)
})
} catch let err {
print(err)
}
}) .resume()
}
}
struct articlesList: Decodable {
let id: Int?
let old_id: Int?
let title: String?
let date: String?
let imageUrl: String?
let has_video: Int?
}