ioshttprequestswift5urlrequest

URLRequest in Swift5


I'm using the OpenWeather Current Weather Data Api, and trying to make a url request to get json data from the api in Swift5. I need to print the json data. Here is some code I found on the internet that I have been trying to use, but has not been working.

Note: I do NOT want to use any external libraries. like alamofire.


let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid={APIKEY}")!
var request = URLRequest(url: url)

let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in

    if let error = error {
        print(error)
    } else if let data = data {
        print(data)
    } else {
        print("nope")
    }
}

task.resume()

Solution

  • The Openweathermap API documentation is a bit misleading, the expression {API key} indicates the API key without the braces.

    Insert the key with String Interpolation

    let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=\(APIKEY)")!
    

    The URLRequest is not needed and dataTask returns either valid data or an error

    let task = URLSession.shared.dataTask(with: url) { (data, _, error) in
        if let error = error { print(error); return } 
        print(String(data: data!, encoding: .utf8)!)
    }
    task.resume()
    

    To display the data create an appropriate model and decode the data with JSONDecoder