I've created a Network manager where I do send a request and getting the success result as below:
func request<T: Decodable>(url: ServiceURL,
method: HTTPMethod,
parameters: Parameters?,
encoding: ParameterEncoding,
responseObjectType: T.Type,
success: @escaping (T) -> Void,
failure: @escaping (AFError) -> Void) {
let requestURL = StaticStringsList.baseURL + url.description + StaticStringsList.apiKeyParam
let request = AF.request(
requestURL,
method: method,
parameters: parameters,
encoding: encoding,
headers: nil
)
request
.validate()
.responseDecodable(of: T.self) { response in
switch response.result {
case .success(let data):
success(data)
case .failure(let error):
failure(error)
}
}
}
Later on I use it in my viewModel and that works fine so far.
private func movieDetailAPIHandler() {
NetworkManager.shared.request(
url: .movieDetail(model.id.string()),
method: .get,
parameters: nil,
encoding: URLEncoding.default,
responseObjectType: MovieDetailResponse.self,
success: { [weak self] result in
self?.movieDetailResult = result
},
failure: { error in
print("error in tvdetail \(error)")
}
)
}
What I want to do is, get rid of the function that is called in viewModel.(ex: movieDetailAPIHandler() in above.)
What I mean by that is, create a APIHandler class where I call NetworkManager's request function, and handle every response type there.
APIHandlers class below is what I'm trying to do. I've also created an enum called ServiceURL which brings the related url according to the input of apiHandler() function as below:
class APIHandlers {
static let shared = APIHandlers()
func apiHandler<T: Codable>(with idServiceURL: ServiceURL, type: T, success: @escaping ((T) -> Void)) {
NetworkManager.shared.request(
url: idServiceURL,
method: .get,
parameters: nil,
encoding: URLEncoding.default,
responseObjectType: T.self,
success: success,
failure: { _ in
print("cast alınamadı")
}
)
}
Everything looks good so far but when I try to call the apiHandler() function, compiler gives me the error says "Type 'CastResponse.Type' cannot conform to 'Decodable'" And besides that, xcode doesnt know what my request Type is.(Checkout the image below.)
APIHandler Function inside my viewModel:
APIHandlers.shared.apiHandler(with: .movieCast(model.id.string()), type: CastResponse) { response in
}
So what I try to do a generic apiHandler function which I can use it with enums and different response Types so I can use it in every module.
What can I do to achieve that? Thanks.