Moon-Duck-Org / MoonDuckFE-iOS

B-Side 405 포텐데이 - Moon Duck iOS
0 stars 0 forks source link

[REFACTOR] Request TargetType에 추가 #22

Closed SuniDev closed 4 months ago

SuniDev commented 4 months ago

💡 요약

참고 소스

` 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)")
    }
}