Create a NSObject class and and create a class level function inside it. and call it from any other class
import Alamofire
class Network: NSObject {
class func API_PostData(_ strURL: String, parameter Params: NSDictionary, successWithStatus1Closure: @escaping (AnyObject?) -> (), successWithStatus0Closure: @escaping (AnyObject?) -> (), failurClosure: @escaping (String?)-> ())
{
let Param: [String: Any] = Params.mutableCopy() as! [String : Any]
let complite_url = BASE_URL+strURL
if Reachability.isConnectedToNetwork(){
Alamofire.request(complite_url, method: .post, parameters: Param ,encoding: JSONEncoding.default).responseJSON {
response in
if(response.result.error != nil)
{
let error = response.result.error
if (error?.localizedDescription == "The request timed out."){
failurClosure("The request timed out.");
return
}
if (error?.localizedDescription == "Could not connect to the server."){
failurClosure("Could not connect to the server.");
return
}
if (error?.localizedDescription == "The network connection was lost."){
failurClosure("The network connection was lost.");
return
}
}
let dictResponse = response.result.value as? NSDictionary
print("Response",response)
if dictResponse is Dictionary<AnyHashable,Any> {
print("Yes, it's a Dictionary")
}
else{
print("No, it's a not a Dictionary")
failurClosure("Active internet connection required")
return
}
let isSuccess = dictResponse!["success"] as! Int
if isSuccess == 1
{
successWithStatus1Closure(dictResponse)
}else{
successWithStatus0Closure(dictResponse)
}
}
}else {
print("Active internet connection required");
failurClosure("Active internet connection required")
return
}
}
}
and use it like
Network.API_PostData
and xCode will autocompleted the method
Uses Example in your view controller create a method
func callApi(){
let para = ["user_id" : USER_ID_STR,
"page" : String(page),
"item_per_page" : "15"
] as NSDictionary
SVProgressHUD.show()
GlobalClass.API_PostData("notifications/activities", parameter: para, successWithStatus1Closure: { (response) in
print("response \(response)")
SVProgressHUD.dismiss()
}, successWithStatus0Closure:{ (response) in
print("response \(response)")
SVProgressHUD.dismiss()
}, failurClosure: { (error) in
print("error \(error ?? "ddd")")
GlobalClass.showAlert(alertTitle: "", alertMsg: error!, view: self)
SVProgressHUD.dismiss()
})
}
and call it like
callApi()