Last active
January 13, 2020 07:08
-
-
Save ashishkakkad8/94edb68144f7d93ecc10 to your computer and use it in GitHub Desktop.
Alamofire - SwiftyJSON Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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) | |
} | |
} | |
} | |
} |
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
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are there any example of use? Handling the success and failure async was the problem for me.