#3 Alamofire RxSwift HTTP REST Api Integration - RxSwift MVVM Coordinator iOS App
Alamofire
를 통한 네트워크 통신import Alamofire
import Foundation
protocol HttpRouter {
var baseUrlString: String { get }
var path: String { get }
var method: HTTPMethod { get }
var headers: HTTPHeaders? { get }
var parameters: Parameters? { get }
func body() throws -> Data?
func request(usingHttpService service: HttpService) throws -> DataRequest
}
extension HttpRouter {
var parameters: Parameters? { return nil }
var headers: HTTPHeaders? { return nil }
func body() throws -> Data? { return nil }
func asUrlRequest() throws -> URLRequest {
var url = try baseUrlString.asURL()
url.appendPathComponent(path)
var request = try URLRequest(url: url, method: method, headers: headers)
request.httpBody = try body()
return request
}
func request(usingHttpService service: HttpService) throws -> DataRequest {
return try service.request(asUrlRequest())
}
}
Alamofire
사용import Foundation
import Alamofire
protocol HttpService {
var sessionManager: Session { get set }
func request(_ urlRequest: URLRequestConvertible) -> DataRequest
}
HttpService
또한 위의 라우터에서 사용하는 프로토콜import Alamofire
class AirportHttpService: HttpService {
var sessionManager: Session = Session.default
func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
return sessionManager.request(urlRequest).validate(statusCode: 200..<400)
}
}
import Alamofire
enum AirportHttpRouter {
case getAirports
}
extension AirportHttpRouter: HttpRouter {
var baseUrlString: String {
return "https://gist.githubusercontent.com/tdreyno/4278655/raw/7b0762c09b519f40397e4c3e100b097d861f5588"
}
var path: String {
switch self {
case .getAirports: return "airports.json"
}
}
var method: HTTPMethod {
switch self {
case .getAirports: return .get
}
}
}
import Foundation
import RxSwift
protocol AirportAPI {
func fetchAirports() -> Single<AirportResponse>
}
Single
로 감싸주기 위한 RxSwift
import Foundation
import RxSwift
class AirportService {
static let shared: AirportService = AirportService()
private lazy var httpService = AirportHttpService()
private init() {}
}
extension AirportService: AirportAPI {
func fetchAirports() -> Single<AirportResponse> {
return Single.create { [httpService] single -> Disposable in
do {
try AirportHttpRouter
.getAirports
.request(usingHttpService: httpService)
.responseDecodable(of: AirportResponse.self, completionHandler: { response in
switch response.result {
case .success(let airports):
print("Airports: \(airports)")
single(.success(airports))
case .failure(let error): print(error.localizedDescription)
}
})
} catch {
}
return Disposables.create()
}
}
}
httpService
및 AirportService
싱글턴을 통해 공항 데이터를 패치func process() {
airportService
.fetchAirports()
.map({print("Airports: \($0)")})
.subscribe()
.disposed(by: disposeBag)
}