Using PromiseKit and Alamofire For Clean API Layer

      No Comments on Using PromiseKit and Alamofire For Clean API Layer

Promise kit and Alamofire when used together create a very powerful and flexible API Layer

Every App interacting with web services contains an API layer which separates API handling from the rest of the application logic.

Usually, the API layer is implemented using delegates or escaping closures. Escaping closures and delegates are neat but we can achieve a neater solution by using Alamofire and PromiseKit

Given below is a sample APIManager

import UIKit
import PromiseKit
import Alamofire
//enum to keep all paths organised
enum RequestEndPoint: String{
    case login = "/Login"
}
class APIManager: NSObject {
    static let manager:APIManager = APIManager();
    let baseURL  = "YOUR BASE URL"
    
    func hitApi(endPoint:RequestEndPoint,parameters:[String:Any])->Promise<Any>{
        switch endPoint {
        case .login:
            //do any cutom thingy unique to login
            return api(url:URL(string:baseURL + endPoint.rawValue)!, dict: parameters)
        }
    }
    func api(url:URL,dict:[String:Any])->Promise<Any>{
        return Promise<Any>{seal in
            var request =  URLRequest(url:url)
            request.setValue("application/json", forHTTPHeaderField:"Content-Type")
            let data = try JSONSerialization.data(withJSONObject:dict , options: [])//PromiseKit will take care of throw
            request.httpBody=data
            //request is done by now
            Alamofire.request(request)
            .validate()
                .responseJSON(completionHandler: { responseData in
                    switch responseData.result{
                    case .success:
                        seal.fulfill(responseData.data!)
                    case .failure:
                        seal.reject(responseData.error!)
                    }
                })
        }
    }
    
}

In the above example, we created an API manager class. Let’s see its usage

override func viewDidLoad() {
    super.viewDidLoad()
    
    _=APIManager.manager.hitApi(endPoint: .login, parameters: ["UserName":"Amarendra","Password":"LoveAll"])
        .done({ (Data) in
            //parse data here
        })
        .catch({ (error) in
            //do error handling
        })
        .finally {
            //remove any activity indicator
    }
    // Do any additional setup after loading the view, typically from a nib.
}

 

A pat on the back !!