获取当前位置的温度 API swift

Get temperature of current location API swift

任何人都可以帮我解决这个 API 代码。除了一个错误,我什么都搞定了。

这是我的代码:

 let APIUrl = NSURL(string:"https://api.openweathermap.org/data/2.5/weather?   lat=35&lon=150&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric")
 var request = URLRequest(url:APIUrl! as URL)

 let task = URLSession.shared.dataTask(with: request as URLRequest)

 guard let data = Data else {return}

 let decoder = JSONDecoder()

 let weatherData = try decoder.decode(MyWeather, from: data)

 let ggtemp = weatherData.main?.temp
    print(ggtemp, "THIS IS THE TEMP")
        DispatchQueue.main.async {
        tempDisplay.text = String (ggtemp) + " c"
     }
 }

Image of error

修复 "let data = data" 错误后,"let task = URLSesss..."

出现错误

如有任何帮助,我们将不胜感激。提前致谢。

试试这个代码

let APIUrl = NSURL(string:"https://api.openweathermap.org/data/2.5/weather?lat=35&lon=150&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric")
var request = URLRequest(url:APIUrl! as URL)
request.httpMethod = "GET"

let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in

    if (error != nil) {
        print(error ?? "Error is empty.")
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse ?? "HTTP response is empty.")
    }

    guard let responseData = data else {
        print("Error: did not receive data")
        return
    }

    do {

        let weatherData = try JSONDecoder().decode(MyWeather.self, from: responseData)
        let ggtemp = weatherData.main?.temp
        print(ggtemp, "THIS IS THE TEMP")
        DispatchQueue.main.async {
            tempDisplay.text = String (ggtemp) + " c"
        }

    } catch  {
        print("error parsing response from POST on /todos")
        return
    }

})

dataTask.resume()