How to create a wrapper for Alamofire and SwiftyJSON? Swift – iOS

This blogpost updated with Swift 3 – Xcode 8 – iOS 10 – Alamofire 4.0

AFWrapper
AFWrapper

I have posted a basic tutorial about Alamofire and SwiftyJSON How to use Alamofire and SwiftyJSON with Swift?
And some day before we have learned about Use of Blocks(Closures) or Completion Handlers with Function in Swift – iOS
Let’s combine both the topics to make a WRAPPER of Alamofire and SwiftyJSON.

Let’s Begin to Wrap

  1. Create an NSObject class
  2. Go to File > New > File… and add a Swift NSObject class

  3. Import respective modules/frameworks
  4. Import the frameworks that you want to use with this wrapper.

  5. Create a Function
  6. Create a function with the use of Completion Handler/Closures/Blocks
    Following is a sample of GET URL call with Alamofire and response object will be return to a success or failure closure/block respectively. If response is success then return a SwiftyJSON object with the success block.

That’s It. Let’s Use It

By this way we can use the code reusability.
Following is the sample with the use of the wrapper :

Gist with Alamofire-SwiftyJSON – GET and POST Requests


//
// AFWrapper.swift
// AFSwiftDemo
//
// Created by Ashish on 10/4/16.
// Copyright © 2016 Ashish Kakkad. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class AFWrapper: NSObject {
class func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}

view raw

AFWrapper.swift

hosted with ❤ by GitHub

In addition you can also integrate the Loader/HUD with the web service call to display web service is processing right now.
Happy Coding 🙂