Protocol 설계 (추후 수정 필요.. ㅠ )
protocol API {
associatedtype RequestData: APIData
var baseURL: URL { get }
var header: [String: String]? { get }
}
protocol APIData {
associatedtype Data: Codable
var path: String { get }
var method: HTTPMethod { get }
var requestData: Data { get }
}
Network Error 정의 (TODO: Alarmofire에서 제공하는 에러로 수정)
enum NetworkError: Error {
case urlError
case dataError
case parseError
case networkError
}
final class NetworkManager {
private let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
typealias NetworkCompletion<T: Decodable> = (Result<T, NetworkError>) -> Void
func requestData<T: Decodable>(urlString: String, completion: @escaping NetworkCompletion<T>) {
guard let url = URL(string: urlString) else {
completion(.failure(.urlError))
return
}
performRequest(url: url) { result in
completion(result)
}
}
private func performRequest<T>(url: URL, completion: @escaping NetworkCompletion<T>) {
AF.request(url, method: .get)
.responseData { response in
switch response.result {
case .success(let data):
if let parseData = self.parseJSON(data: data) as T? {
completion(.success(parseData))
} else {
completion(.failure(.parseError))
}
case .failure(let error):
print(error.localizedDescription)
completion(.failure(.networkError))
}
}
}
private func parseJSON<T: Decodable>(data: Data) -> T? {
do {
let result = try decoder.decode(T.self, from: data)
return result
} catch {
return nil
}
}
}