final class NetworkManager {
static let shared = NetworkManager()
private init() {}
private let provider = MoyaProvider<PokemonAPI>()
func fetch<T: Decodable>(endpoint: PokemonAPI, type: T.Type) -> Single<T> {
return Single.create { [weak self] single in
guard let self = self else {
single(.failure(NSError(domain: "NetworkManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "Self is nil."])))
return Disposables.create()
}
self.provider.request(endpoint) { result in
switch result {
case .success(let response):
do {
let decodedData = try JSONDecoder().decode(T.self, from: response.data)
single(.success(decodedData))
} catch {
single(.failure(error))
}
case .failure(let error):
single(.failure(error))
}
}
return Disposables.create()
}
}
}
PokemonAPI
와 같은 Moya TargetType
을 정의한다.
enum PokemonAPI {
case fetchPokemonList(limit: Int, offset: Int)
}
extension PokemonAPI: TargetType {
var baseURL: URL {
return URL(string: "https://pokeapi.co/api/v2")!
}
var path: String {
switch self {
case .fetchPokemonList(let limit, let offset):
return "/pokemon?limit=\(limit)&offset=\(offset)"
}
}
var method: Moya.Method {
return .get
}
var task: Task {
return .requestPlain
}
var headers: [String: String]? {
return ["Content-Type": "application/json"]
}
}
NetworkManager를 사용해 데이터를 가져온다.
import RxSwift
let disposeBag = DisposeBag()
let endpoint = PokemonAPI.fetchPokemonList(limit: 10, offset: 0)
NetworkManager.shared.fetch(endpoint: endpoint, type: PokemonList.self)
.subscribe { result in
switch result {
case .success(let data):
print("데이터: \(data)")
case .failure(let error):
print("에러: \(error.localizedDescription)")
}
}
.disposed(by: disposeBag)
오늘 밤 당신의 APIKey를 훔치겠습니다.