快速获取当前位置API的温度

时间:2018-10-21 05:12:06

标签: ios swift4 xcode9.4

任何人都可以通过此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

一旦我解决了“让数据=数据”错误,我就会收到关于“让任务= URLSesss ...”的错误

任何帮助将不胜感激。预先感谢。

1 个答案:

答案 0 :(得分:0)

尝试此代码

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