[iOS – Swift] Create API Wrapper With Alamofire ?>

[iOS – Swift] Create API Wrapper With Alamofire


In this section I’ll show you how to create an API Wrapper with Alamofire library in Swift. If you want to develop in Objective-C then you should check this post https://hantran.info/ios-create-api-wrapper-with-afnetworking/

Let’s dive into it!

1. Installation

Once again, I recommend to use Pod to install external library.

Open the Pod file of your project and use this code to install Alamofire:

Then open terminal and:

Installation should be done without any errors.

For others way to install, please kindly to check it here: https://github.com/Alamofire/Alamofire

2. Create API Wrapper

Here is the simple class which I created for demonstrate demo.

Okay, I’ll dive into this class for clearly understanding.

The main function of this class is the getCategories method, our API.

Take a look at it we can see that I created a post data first (params), then passed it to the request method of Alamofire.

The request method of Alamofire take some requirement parameter at you can see in the code above. First is the request method, it’s can be GET, POST, PUT, DELETE… Next is our api URL, then parameters, encoding and the headers. You can passed indeed information here before you make the request to API server.

In this class I provided the parseJsonData method which using the default Json parser of Swift to demonstrate how to parse JSon data from server, you can take a look at your self to understand the code, it’s simple so I’ll not explain more.

3. Use the API

From now on, using the API can be easier:

So simple, no need to explain right? :)

Please note that all of codes above is just for demonstrate only, you should handle the errors when request or anything else.


Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *