Home > Enterprise >  URLRequest in Swift5
URLRequest in Swift5

Time:03-04

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

CodePudding user response:

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

CodePudding user response:

So, at first you should be aware that you are registered and already have your own API Key. The main reason that can occur here for not opening link is that You are using a Free subscription and try requesting data available in other subscriptions . And for future if you want to do just get request you don't need to do session.dataTask(with: request), the session.dataTask(with: url) will be OK.)

Here is simpler way of your code.

guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid={APIKEY}") else {return}
    let session = URLSession.shared
    let task = session.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print(error)
        } else if let data = data {
            print(data)
        } else {
            print("nope")
        }
    }
    task.resume()
  • Related