https://www.zehye.kr/ios/2020/04/01/12iOS_alamofire/
func request(_ convertible: URLConvertible, // URL
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let err = error { // 에러 체크
print(" ---> error : \(APIError.stationAPIError)")
onComplete(.failure(err))
}
guard let data = data else { // data nil 체크
onComplete(.failure(APIError.stationAPIError))
return
}
let json = JSON(data)
guard let station: String = json["response"]["body"]["items"][0]["stationName"].string else {
onComplete(.failure(APIError.stationAPIError))
return
}
onComplete(.success(station))
}.resume()
AF.request(url, method: .get, encoding: URLEncoding.default)
.responseJSON{ (response) in
switch response.result{ // result를 통해 성공 여부를 구분할 수 있음
case .success(let data):
let json = JSON(data)
guard let station: String = json["response"]["body"]["items"][0]["stationName"].string else {
onComplete(.failure(APIError.stationAPIError))
return
}
onComplete(.success(station))
case .failure(let error):
print(" ---> error : \(APIError.stationAPIError)")
onComplete(.failure(error))
}
}
// 받아온 Json 파일
// {"response":
// {"body":
// {"items":[
// 받아온 json을 [String: Any]로 변환하겠다.
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else{
return
}
responses = json["response"] as! [String : Any]
bodys = responses["body"] as! [String : Any]
items = bodys["items"] as! [[String : Any]]
let item: [String : Any] = items[0]
guard let station: String = item["stationName"] as? String else {
onComplete(.failure(APIError.stationAPIError))
return
}
guard let station: String = json["response"]["body"]["items"][0]["stationName"].string else {
onComplete(.failure(APIError.stationAPIError))
return
}
static func fetchFineDust(stationName: String, onComplete: @escaping (Result<FineDustAPIData, Error>) -> Void){
let url = fineDustURL(stationName: stationName)
AF.request(url, method: .get, encoding: URLEncoding.default)
.responseJSON{ (response) in
switch response.result{
case let .success(data):
let json = JSON(data)
guard let fineDustValue: String = json["response"]["body"]["items"][0]["pm10Value"].string else {
print("finedust Error")
onComplete(.failure(APIError.finedustAPIError))
return
}
guard let ultraFineDustValue: String = json["response"]["body"]["items"][0]["pm25Value"].string else {
print("ultrafinedust Error")
onComplete(.failure(APIError.finedustAPIError))
return
}
guard let dateTime: String = json["response"]["body"]["items"][0]["dataTime"].string else {
print("dateTime Error")
onComplete(.failure(APIError.finedustAPIError))
return
}
let response = fineDustAPIData(dateTime: dateTime, fineDustValue: fineDustValue, ultraFineDustValue: ultraFineDustValue, stationName: stationName)
onComplete(.success(response))
case let .failure(error):
onComplete(.failure(error))
}
}
}
static func loadFineDust(stationName: String) -> Observable<FineDustAPIData>{
return Observable.create{ emitter in
self.fetchFineDust(stationName: stationName){ result in
switch result {
case let .success(finedust):
emitter.onNext(finedust)
emitter.onCompleted()
case let .failure(error):
emitter.onError(error)
}
}
return Disposables.create()
}
}
lazy var observable = PublishRelay<FineDustAPIData>()
func loadFineDust(latitude: Double, longtitude: Double, mode: FineDustVCMode){
_ = APIService.loadTM(latitude: latitude, longtitude: longtitude)
.flatMap{ tm in APIService.loadStation(tmX: tm.tmX, tmY: tm.tmY)}
.flatMap{ station in APIService.loadFineDust(stationName: station)}
.take(1)
.subscribe(onNext:{ [weak self] response in
self?.observable.accept(response)
})
}
fineDustViewModel.observable
.observe(on: MainScheduler.instance)
.subscribe(onNext:{ [weak self] in
self?.configureView($0)
self?.setProgressView($0)
})
.disposed(by: disposeBag)