호출
tempNearCinemas
에 값이 들어오면 실행
- $0 옵셔널 바인딩을 해주고 닐일 경우
Observable<CinemaSchedule>.empty()
요 형태로 리턴을 해줘야 타입이 맞음
- 얻은 값은
tempCinemaSchedule
로 전달하고 구독이 일어나면 값을 넘겨주도록
tempNearCinemas
.flatMap {
guard let nearestCinema = $0.first else {
return Observable<CinemaSchedule>.empty()
}
let date = "2024-05-08"
return CinemaService.shared.fetchCinemaSchedule(cinema: nearestCinema, date: date)
.take(1)
}
.subscribe(onNext: tempCinemaSchedule.onNext(_:))
.disposed(by: disposeBag)
API Call
firstIndex(where:)
함수 사용해서 결과 리스트에 이미 현재 영화 이름이 들어있는지 확인해서 있으면 결과리스트에 타임테이블에만 추가해주도록
class CinemaService {
static let shared = CinemaService()
private init() {}
func fetchCinemaSchedule(cinema: IndieCinema, date: String) -> Observable<CinemaSchedule> {
return Observable<CinemaSchedule>.create { emitter in
let urlString = "<https://www.dtryx.com/cinema/showseq_list.do?cgid=FE8EF4D2-F22D-4802-A39A-D58F23A29C1E&ssid=&tokn=&BrandCd=\\(cinema.code[0])&CinemaCd=\\(cinema.code[1])&PlaySDT=\\(date)>"
print(urlString)
URLSession.shared.dataTask(with: URL(string: urlString)!) { data, response, error in
if let error = error {
emitter.onError(error)
}
guard let data = data else {
let response = response as! HTTPURLResponse
let error = NSError(domain: "No Data", code: response.statusCode)
emitter.onError(error)
return
}
if let movieScheduleInfos = self.ParseJSON(data: data) {
var cinemaSchedule: [MovieSchedule] = []
for info in movieScheduleInfos {
if let firstIndex = cinemaSchedule.firstIndex(where: {$0.name == info.MovieNm}) {
cinemaSchedule[firstIndex].timeTable.append(info.StartTime)
} else {
cinemaSchedule.append(MovieSchedule(info: info))
}
}
print(cinemaSchedule)
emitter.onNext(cinemaSchedule)
} else {
let error = NSError(domain: "Parsing Error", code: 0)
emitter.onError(error)
}
}.resume()
return Disposables.create()
}
}
func ParseJSON(data: Data) -> [MovieScheduleInfo]? {
do {
let response = try JSONDecoder().decode(MovieScheduleData.self, from: data)
return response.Showseqlist
} catch {
print(error.localizedDescription)
return nil
}
}
}
- 몇가지 잔재주들
- typealias 사용해보고
- 생성자에 MovieScheduleInfo 넣으면 MovieSchedule 로 바뀌도록 편리하게!
typealias CinemaSchedule = [MovieSchedule]
struct MovieSchedule {
let name: String
let imageUrl: String
var timeTable: [String]
let code: String
init(info: MovieScheduleInfo) {
self.name = info.MovieNm
self.imageUrl = info.Url
self.timeTable = [info.StartTime]
self.code = info.MovieCd
}
}