-
rxSwift + Alamofire 코드iOS 2018. 12. 2. 17:36반응형
rxSwift도 슬슬 공부해보려구 합니다..
어렵네요 끙
https://www.netguru.co/codestories/networking-with-rxswift
해당 코드는 네트워킹을 rxSwift로 짠 건데..
제너릭이나 설계나 굉장히 잘하셨더라구요...
여기서 보내는 코드만
제가 자주 쓰는 Alamofire로 고쳐보았습니다.
//
// APIService.swift
// iOS-todoApp
//
// Created by 세상 on 02/12/2018.
// Copyright © 2018 세상. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import Alamofire
public enum RequestType : String{
case GET, POST
}
protocol ApiRequest{
var method : RequestType { get }
var path : String { get }
var parameters : [String : String ]{ get}
}
extension ApiRequest {
func request(with baseURL : URL) -> URLRequest {
guard var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false) else {
fatalError("Unable to create URL compoenents")
}
components.queryItems = parameters.map{
URLQueryItem(name: String($0), value: String($1))
}
guard let url = components.url else {
fatalError("Could not get url")
}
let request : URLRequest = {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.addValue("application/json", forHTTPHeaderField: "Accept")
return request
}()
return request
}
}
class ApiService {
let baseURL = URL(string: "http://universities.hipolabs.com/")!
func send<T: Codable>(apiRequest : ApiRequest) -> Observable<T> {
return Observable<T>.create { observer in
let request = apiRequest.request(with: self.baseURL)
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in
do {
let model : T = try JSONDecoder().decode(T.self, from: data ?? Data())
observer.onNext(model)
} catch let error {
observer.onError(error)
}
observer.onCompleted()
}
task.resume()
return Disposables.create {
task.cancel()
}
}
}
/**
Alamofire 로 짜기
**/
func get<T: Codable>(apiRequest: ApiRequest) -> Observable<T> {
return Observable<T>.create { observer in
let request = apiRequest.request(with: self.baseURL)
let dataRequest = Alamofire.request(request).responseData{
response in
switch response.result {
case .success(let data) :
do {
let model : T = try JSONDecoder().decode(T.self, from: data)
observer.onNext(model)
} catch let error {
observer.onError(error)
}
case .failure(let error):
observer.onError(error)
}
observer.onCompleted()
}
return Disposables.create {
dataRequest.cancel()
}
}
}
/**
searchController.searchBar.rx.text.asObservable()
.map { ($0 ?? "").lowercased() }
.map { UniversityRequest(name: $0) }
.flatMap { request -> Observable<[UniversityModel]> in
return self.apiClient.send(apiRequest: request)
}
.bind(to: tableView.rx.items(cellIdentifier: cellIdentifier)) { index, model, cell in
cell.textLabel?.text = model.name
}
.disposed(by: disposeBag)
**/
}
반응형'iOS' 카테고리의 다른 글
iOS 네이밍 컨벤션 (0) 2018.12.11 Swift에서 디스크 캐시, 메모리 캐시란 (0) 2018.12.03 GCD의 개념 (0) 2018.11.30 [iOS] iOS 면접 질문 인터뷰 모음. (0) 2018.11.30 UIAlertViewController 에서 여러 줄의 인풋(UITextView) 을 받는 방법이 없을까? (0) 2018.10.12