Network Request in Swift

Diana
3 min readJun 3, 2020
Photo by Volodymyr Hryshchenko on Unsplash

‘If you need anything, just aaask.’ Do you still remember this quote from movie-Kong Fu Panda, Mr.Ping, a happy-go-lucky goose, Po’s adoptive father. I do not know about you, but i really feel awesome when dealing with someone or something so promising.

In this article, let’s take a close look at Network request in swift.

We are going to write some code in Xcode playground to demonstrate how promising network request can be in swift.

The API that we are going to fetch data from is here.

Step 1 Register an account on website https://newsapi.org/ so that you could have a API key to play with.

The following is a sample URL from newsapi. You noticed at last & that is says apiKey= . This is the place for your own API key.

http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-03&sortBy=publishedAt&apiKey=3b2ec6050fdf4c53b0500c4bfed546be

Step 2 Go to Xcode and create a playground. Yes, we are going to use playground to demonstrate the network request and get data back from the given URL.

Step 3 This is the URL that we are going to use to fetch the data

http://newsapi.org/v2/everything?q=covid-19&from=2020-06-01&to=2020-06-02sortBy=popularity&language=en&apiKey=3b2ec6050fdf4c53b0500c4bfed546e

This URL is requesting information in the following manner:

  • Give me everything (news) about COVID-19
  • From 1st June to 2nd June
  • Language is in English
  • last bit is your precious apiKey (Do not copy my apiKey as it won’t be valid for you)

So, how do you know this URL is working. Easy to test out.

  • Download Chrome Extension JSON Viewer Awesome if you use Chrome
  • Otherwise, any JSON formatter tool will do
  • Copy your URL and paste it in your browser address bar , click Enter.

You shall see something like this:

Step 4 In order to make the URL request interesting, we will change the order of those keywords, drop the q=in the original URL , still get the same result.

http://newsapi.org/v2/everything?apiKey=3b2ec6050fdf4c53b0500c4bfed546e&from=2020-06-01&to=2020-06-02sortBy=popularity&language=en

The reason for doing this, is that we can then attach our customisedkeywordto this URL.

This is how we are gonna do it in swift.

Have a read about the API doc on newsApi.org and play around with different combinations to get the relevant data. After all, this is what is happening behind those search bar in the apps that we use daily.

Step 5 We now are ready to perform the request. Data Moment

Step 6 To test out , simply create a NewsManager instance and give it a keyword

In playground, we can see the result is printed out:

Or latest news about apple

Completed !!

Thank you for checking this article up. And don’t forget to give it some claps! 👏🏼👏🏼👏🏼 if you found it helpful.💡

--

--