尝试从 API 获取数据时在 url 中出错

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

我正在尝试从 openweathermap.org 获取数据,但在 url

中出现错误

错误:线程 1:致命错误:在展开可选值时意外发现 nil

这是我的数据:

struct CitiesWeather: Decodable {
    
    var coord : Coordinate?
    
}

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

我的代码:

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()
        
    }
}

这里有2个问题。首先,您的 URL 字符串在斜线和域 http:// api 之间有一个 space。这不是有效的 URL

其次,您在此处强制展开 URL 对象:URL(string: url)!。这不是来自 API 的问题,这是您这边的代码问题。强制展开非常危险,应不惜一切代价避免。您无法捕获这些错误。您需要先检查问题,并可选择解包 URL。例如:

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

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