Mikl.hart
Mikl.hart

Reputation: 57

Get an error in url, when trying to get data from API

I'm trying to get data from openweathermap.org and get an error in url

Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

This is my data:

struct CitiesWeather: Decodable {
    
    var coord : Coordinate?
    
}

struct Coordinate: Decodable {
    
    var longitude: Double
    var latitude: Double
    
}

My code:

class DayWeatherViewModel: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    let url = "http:// api.openweathermap.org/data/2.5/weather?q=London&appid=myAppID"
    getData(from: url)

}

func getData(from url: String) {
        
        let task = URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in //**<--Error in url!**
            guard let data = data, error == nil else {
                print("something went wrong")
                return
            }
            
            var result: CitiesWeather?
            do {
                result = try JSONDecoder().decode(CitiesWeather.self, from: data)
            }
            catch {
                print("failed to convert \(error.localizedDescription)")
            }
            
            guard let json = result else {
                return
            }
            print(json.coord)
            print(json.coord?.latitude)
            print(json.coord?.longitude)
        }
        
        task.resume()
        
    }
}

Upvotes: 0

Views: 1075

Answers (1)

Simon McLoughlin
Simon McLoughlin

Reputation: 8465

There are 2 problems here. First your URL string has a space in it between the slashes and the domain http:// api. This is not a valid URL

Second, you are force unwrapping the URL object here: URL(string: url)! . This is not an issue coming from the API, this is a code issue on your side. Force unwrapping is extremely dangerous and should be avoided at all costs. You can't catch these errors. You need to check for issues first and optionally unwrap the URL. For example:

guard let url = URL(string: "...") else {
    print("Failed to parse URL")
    return
}

URLSession.shared.dataTask(with: url) .....

Upvotes: 0

Related Questions