Basic API Request with Swift 5

Tram Ho

In this article, I will guide people to take photos and display them on the app screen via basic API request.

Let's start by creating a new project.

Here I named the project called requestDemo. The goal that this project wants to aim at is as follows:

After the project has been created, we will go to the storybroad and place an imageView on the screen. At the same time, the constraint to imageView stays full screen and set content mode to Aspect fit as shown:

Next we will drag the IBOutlet for this image to be able to handle it with the following code:

Now everything is ready for us to go into the main topic of the article. In this example I used a picture of the cat I found on Google. This example is quite simple, so most of the code we will put in viewDidLoad() , then people can code a file separately for ease of use in many places. First we will use a class named URL to represent the URL of the prepared image. Create an isntance of this class and paste the URL string there:

Once we have the URL, we will retrieve the data. The URLSession class can handle network requests, let's create a request to retrieve the data. We can completely create a URLSession to edit as we like, but in this simple example we can take advantage of the .share to execute basic GET requests. When we use class URLSession , a network request is called a task and every time we interact with the API we have to work with a similar task.

Now we will create a task and pass it the URL class we created above:

We use URLSession to start a request to the URL that contains the image URL. In this function, completion handle will be helpful in case of handling data with an error. Now we can display images to the screen after running the task, remember that UI elements must always be updated on the main thread:

In Swift 5, there is one more thing called the Result Type returned. Result type is implemented as an enum with two cases, success and failure . Both of these cases are designed in generic form so it is possible to associate to any value you want, but failure must conform with the Error type of Swift. Taking advantage of Réult Type very beneficial when working with asynchronous tasks because before getting the data, we can catch success or failure . We can observe the following simple example:

This is the result of displaying images:

The above is a basic example of using and working with URLs and URLSession, hoping that it will help people in building an effective API management system.

Ref:

https://medium.com/better-programming/basic-api-request-with-swift-4-d8bf829524f https://www.hackingwithswift.com/articles/161/how-to-use-result-in-swift

Share the news now

Source : Viblo