Building Netflix App in Swift 5 and UIKit (Xcode 13, 2021) - Episode 9 - SearchViewController Part 1
UISearchController
사용func getSearchResultContents(with query: String) -> AnyPublisher<[ContentModel], Error> {
guard let url = URL(string: "\(TMDBConstants.baseURL.rawValue)/3/search/movie?api_key=\(TMDBConstants.API_KEY.rawValue)&language=en-US&query=\(query)&page=1") else { return Fail(error: URLError(.badURL)).eraseToAnyPublisher() }
return getDataPublisher(with: url)
}
import Foundation
import Combine
class SearchViewModel {
let resultContentsModel: CurrentValueSubject<[ContentModel], Never> = .init([])
private var cancellables = Set<AnyCancellable>()
init() {
addSubscription()
}
private func addSubscription() {
APICaller
.shared
.getUpcomingContents(with: .movie)
.sink { completion in
switch completion {
case .failure(let error): print(error.localizedDescription)
case .finished: break
}
} receiveValue: { [weak self] movieModels in
self?.resultContentsModel.send(movieModels)
}
.store(in: &cancellables)
}
func getSearchResultContents(with query: String) {
APICaller
.shared
.getSearchResultContents(with: query)
.sink { completion in
switch completion {
case .failure(let error): print(error.localizedDescription)
case .finished: break
}
} receiveValue: { [weak self] resultModels in
self?.resultContentsModel.send(resultModels)
}
.store(in: &cancellables)
}
}
resultContentsModel
퍼블리셔를 업데이트함으로써 뷰 컨트롤러에서 UI 패치private let searchController: UISearchController = {
let vc = UISearchController()
vc.searchBar.placeholder = "검색"
vc.searchBar.searchBarStyle = .minimal
vc.definesPresentationContext = true
return vc
}()
private func setUI() {
view.backgroundColor = .systemBackground
searchController.searchResultsUpdater = self
navigationItem.searchController = searchController
searchController.searchBar.delegate = self
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
DispatchQueue.main.async { [weak self] in
self?.searchController.searchBar.becomeFirstResponder()
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard
let query = searchBar.text,
!query.trimmingCharacters(in: .whitespaces).isEmpty else { return }
viewModel.getSearchResultContents(with: query)
searchController.isActive = false
}
cancel
버튼이 자동으로 클릭, 비활성 상태