For mobile applications it is common enough to connect to a remote server to send and receive data; most of the times we will interact with the server through a REST API.
In Swift we can use Alamofire, the networking library, to simplify our REST calls.

In this post we will see, through examples, the bare minimum necessary to get started quickly with REST calls in Swift 3.

Installing Alamofire

The first step to allow Alamofire to make our lives easier is to add it to our project. Alamofire is available via Cocoapods, Carthage, and even the Swift Package manager.

If you are using Cocoapods you can install it adding this line to your pod file:

pod 'Alamofire'

and run pod install

Carthage users need to add this line to their Cartfile:

github "Alamofire/Alamofire"

And afterwards run the following command:

carthage update

For more information on how to use Cocoapods, or Carthage you can check here.

The simplest Alamofire request

In its simplest form we make a GET request to a URL, and check if the petition was successful, or if the server returned an error. Notice that if we do not specify the method, GET will be used by default.

   let url = "https://myurl.com/posts"
   Alamofire.request(url).responseJSON { response in
            switch response.result {
            case .success:
               print(response)
            case .failure(let error):
                failure(0,"Error")
            }
        }

HTTP methods: GET, POST, PATCH, …

If we do not want to use the default GET, we must pass the method as a parameter to the request like in this example for a POST request:

   Alamofire.request(url, method:.post).responseJSON { response in
            switch response.result {
            case .success:
               print(response)
            case .failure(let error):
                failure(0,"Error")
            }
        }

Adding parameters to the request

Usually we will want to send some parameters with our POST request. For example, take this JSON, that represents a new user to add to our system:

{
    "name": "user1",
    "email": "user1@org"
}

We create a dictionary to represent that information, and add it as a parameter to our request method:

let parameters = [
    "name": "user1",
    "email": "user1@org"
]
let url = "https://myurl.com/posts"
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
            switch response.result {
            case .success:
               print(response)
            case .failure(let error):
                failure(0,"Error")
            }
        }

Notice we had added an extra parameter encoding to specify the format in which the parameters will be sent to the server. In the above example we are sending the data as JSON in the body of the request.

If we wish to send the parameters in the URL the right encoding is URLEncoding.default which will produce a url of this type:

https://myurl.com/posts?name=user1&email=user1@org

URLEncoding.default is Alamofire’s default encoding, so if we do not specify and encoding this one is the one which will be used.

Adding header parameters to the request request

Let’s modify the above example to add some HTTP headers to our request, for example, let’s add the “Content-Type” property to specify that the content we are sending to the server is a JSON:

var headers: HTTPHeaders = [
            "Content-Type": "application/json"
        ]
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default, headers:headers).responseJSON { response in
            switch response.result {
            case .success:
               print(response)
            case .failure(let error):
                failure(0,"Error")
            }
        }

Using a session manager

Using a session manager with the default configuration:

class UserService {
    static let sharedInstance = UserService()
    private var manager: SessionManager

    private init() {
        self.manager = Alamofire.SessionManager.default
    }

func getUsers(completion:@escaping (User?) -> Void, failure:@escaping (Int, String) -> Void)
{
  let url = "https://myurl.com/users"
  self.manager.request(url).responseJSON { response in
    switch response.result {
      case .success:
        var users:[User] = []
        // parse result
        completion(users)
      case .failure(let error):
        failure(0,"Error")
        }
    }
}

Where do we go from here

Having learned the basics on how to do REST requests using Alamofire, next thing should be how to handle error responses.
In the examples above we assume that we did not require any kind of authentication: this will not always be the case: see, for example, how we can do basic authentication with Alamofire.
Also Alamofire is in most cases used together with ObjectMapper, and Realm to map JSON into objects, and save the data in your device.

Also you can use promises with Alamofire through PromiseKit.

Hope it was of help.
If you found this post useful, you can subscribe to my blog (click at the “follow” button at the bottom) so you can be notified of new posts.

Advertisements