` func performRequest(responseType: T.Type, completion: @escaping (Result<T, APIError>) -> Void) {
do {
let urlRequest = try asURLRequest()
AF.request(urlRequest).responseDecodable(of: responseType) { response in
switch response.result {
case .success(let decodedResponse):
completion(.success(decodedResponse))
case .failure(let error):
if let data = response.data, let errorResponse = try? JSONDecoder().decode(APIError.self, from: data) {
completion(.failure(errorResponse))
} else {
completion(.failure(.responseError(error.localizedDescription)))
}
}
}
} catch let error as APIError {
completion(.failure(error))
} catch {
completion(.failure(.unknownError))
}
}`
// 사용 예제
MoonDuckAPI.getPosts.performRequest(responseType: [Post].self) { result in
switch result {
case .success(let posts):
print("Received posts: \(posts)")
case .failure(let error):
print("Error: \(error)")
}
}
💡 요약
참고 소스
` func performRequest(responseType: T.Type, completion: @escaping (Result<T, APIError>) -> Void) {
do {
let urlRequest = try asURLRequest()