- 
      
- 
        Save ashishkakkad8/94edb68144f7d93ecc10 to your computer and use it in GitHub Desktop. 
| // | |
| // 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) | |
| } | |
| } | |
| } | |
| } | 
Are there any example of use? Handling the success and failure async was the problem for me.
Helped me a lot . thanks for this one ,
if someone having issues how to use this just follow the steps below .
swift 4.
import the necessary packages. // SwiftyJSON
enum apiResult{
case sucess
case error
}
`class FetchAPI {
static func getAPI(completion:@escaping (apiResult)->()){
AFWrapper.requestGETURL(url, success: { (JSON) -> Void in
DispatchQueue.global(qos: .userInteractive).async
{
// Background Thread , Save Data Here
                    DispatchQueue.main.async
                        {
                            completionHandler(.sucess)//Main UI Thread ,  Reload your view
                            
                    }
                    
            }
            
        }, failure: { (Error)->Void  in
            print(Error)
            completionHandler(.error)
        })
}
}`
now you can call above class in your ViewController
Eg.
override func viewWillAppear(_animated:Bool)
{
FetchAPI. getAPI{ (result) in
switch result{
case .sucess:
// reload your tableview, collection view
case .error:
//show an error here
}
}
}
Ashish, thanks for this. Im relatively new to swift and am having trouble grasping the concept of closures, specially escaping closures; can you please put in an explanation of how this
class funcwill be called?