API Call in Swift Part 1 πŸš€ | URLSession

Yasir
2 min readJul 31, 2021

--

In this part, we will look a very basic approach to a network call in swift. In later parts we will look at advanced and nice way.

In this article we will look at how we could make a network call in swift for fetching the data from backend services.

We will not be using any third party for network calls, instead we will be using apples own api services URLSession.

Also we will be using openweathermap for fetching a json response of weather information.

Be sure about these things before Integrating API in app

  • Do we need GET method or POST method or Both.
  • A JSON body to know what we are getting and a documentation.
  • API Key and URLs
  • Any thing else, you can comment

Quick Look at something important

DispatchQueue.main.async
DispatchQueue.main.sync

Essentially this just means that sync will block the main thread until the task has finished, async means this will happen on a background thread and update the main thread when it is finished.

Creating our Model

Now we will have to create a model in which we will be storing data by decoding the response data from the api.

This model will be conforming to decodable protocol. Since we dont need to encode something on the api, we will create it as decodable only.

API :- https://openweathermap.org/current

Take a look at the JSON response in above documentation.

If you are not comfortable with the properties name used inside the model, then you can create a coding keys.

Making a Network Call in Swift

For now, we are implementing network call in viewmodel, the better way could be to create a separate class as API_Manager.

  • We are calling the network call function at the class initialisation
  • The api call is pretty straight forward, in later parts we will be making it more structural and scalable and also we will handle the errors properly.
  • We are updating the temp variable on background thread, because we don’t want our main thread to freeze.

Thats it for PART 1

Thanks for Reading πŸ’―

Me on: LinkedIn β€” GitHub

Check this link: https://bit.ly/38HOQeb

--

--