Most iOS apps have to communicate with their backend servers. Alamofire is a very widely used library for making server calls easy and efficient. But your app may have to manage several API calls, a wrapper makes it clean and efficient. so let’s learn how to create one.
Assuming you have created a new Xcode project and initialised CocoaPods.
Add these dependencies to Podfile
pod 'Alamofire' pod 'Alamofire-SwiftyJSON'
Create a new Swift file named AFWrapper.swift
import UIKit import Alamofire import SwiftyJSON import Alamofire_SwiftyJSON class AFWrapper: NSObject { static let sharedInstance = AFWrapper() func cancelAllRequests() { let sessionManager = Alamofire.SessionManager.default sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in dataTasks.forEach { $0.cancel() } uploadTasks.forEach { $0.cancel() } downloadTasks.forEach { $0.cancel() } } } func requestGET(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) { Alamofire.request(strURL) .responseSwiftyJSON(completionHandler: { dataResponse in if dataResponse.result.isSuccess { let resJson = JSON(dataResponse.result.value!) success(resJson) } if dataResponse.result.isFailure { let error : Error = dataResponse.result.error! failure(error) } }) } func requestPOST(_ 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) .responseSwiftyJSON(completionHandler: { dataResponse in if dataResponse.result.isSuccess { let resJson = JSON(dataResponse.result.value!) success(resJson) } if dataResponse.result.isFailure { let error : Error = dataResponse.result.error! failure(error) } }) } }
Example: Using it in your ViewController
AFWrapper.sharedInstance.requestGET(MY_API_URL, success: { (json) in //PARSE DATA. if let myjson = json.array { for itemobj in myjson ?? [] { //parse and add obj } } }, failure: { (error) in print(error) })
If you want to cancel all current Alamofire requests:
AFWrapper.sharedInstance.cancelAllRequests()
For parsing data, I recommend you to go through this.
Leave A Comment