class ApiManager {
let url = "https://15f1-61-246-140-18.in.ngrok.io/Legal251AppAPI_IOS/api/lgapp/index.php?parameter=sendotp"
static let sharedInstance = ApiManager()
func callingApi(signUp : myModel){
let headers: HTTPHeaders = [
"Authkey": Secrets.AuthKey
]
AF.request(url, method: .post, parameters:signUp , encoder: JSONParameterEncoder.default, headers: headers).response{
response in debugPrint(response)
}
}
}
My response
{
"code": 200,
"status": "success",
"message": "SMS IS SENT",
"data": [
{
"status": 1,
"number": "9999911144"
}
]
}
My success response is coming in Data array
I tries to make the network class as generic but in that i am not able to make generic parameter for post the body in api
Here my signUp Model which my body of api
struct myModel: Encodable{
var number : String = String()
var action :String = String()
}
I need to achieve the generic class for networking I explored a lot but didn't got upto the mark answer
I hope here I will get
Thankyou In advance
CodePudding user response:
The API responseJSON
is deprecated and just response
returns Data
.
The most recommended API however is responseDecodable
which decodes the JSON directly into a model.
You can make your API call generic with
class ApiManager {
let url = "https://15f1-61-246-140-18.in.ngrok.io/Legal251AppAPI_IOS/api/lgapp/index.php?parameter=sendotp"
static let sharedInstance = ApiManager()
func callingApi<Input: Encodable, Output: Decodable>(signUp : Input, type: Output.Type){
let headers: HTTPHeaders = [
"Authkey": Secrets.AuthKey
]
AF.request(url, method: .post,
parameters: signUp,
encoder: JSONParameterEncoder.default,
headers: headers).responseDecodable(of: Output.self, decoder: JSONDecoder()) { response in
switch response.result {
case .success(let result): print(result)
case .failure(let error): print(error)
}
}
}
}
In the type
parameter pass the type of the root object for example Response.self