MainViewController에 구현되어 있는 didSelectedItemAt()
함수는 cell을 클릭 시indexPath
를 통해 클릭한 cell에 대한 좌표를 알 수 있다.
수 많은 cell 중에 사용자가 클릭한 cell을 알기 위해서 stroyIDs[indexPath.item]
을 통해 storyID번호를 가져올 수 있다.
클릭한 cell에 Detail page로 이동하기 위해서 StoryViewController
를 생성하여 sotryID
와 delegate
를 인자로 넘긴다.
func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath
) {
let selectedItem = storyIDs[indexPath.item]
print(selectedItem)
let svc = StoryViewController(selectedItem, restProcessor)
navigationController?.pushViewController(svc, animated: true)
}
Detail Page로 이동하기 위해서 StoryViewController.swfit
를 만들었다.
convenience init(_ storyId: Int,
_ restProcessor: RestProcessor) {
self.init()
self.storyId = storyId
self.restProcessor = restProcessor
setup()
}
setup()
함수에서는 Hacker News
에 있는 글을 클릭하면 특정 url
로 이동하게 되는데 이때 WebView
로 띄워주어야 하기 때문에 webivew.uiDelegate
를 지정해주고, 해커뉴스 서버와 통신하기 위해 restProcessor를 delegate
로 지정해준다.
func configureWebView() {
webView.uiDelegate = self
}
func configureRestProcessor() {
self.restProcessor.delegate = self
self.restProcessor.fetchData(urlString: ProjectURL.getStory(itemNumber: storyId).description, usage: .getStory(itemNumber: storyId))
}
RestProtocolDelegate
서버에서 정상적으로 데이터를 가져오면 가져온 데이터를 파싱 후 url과 텍스트에 뿌려준다.
url
과 text
중 둘 중 하나의 값이 서버에서 넘어온다.
url로 넘어올 시에는 WebView
로 text로 넘어올 시에는 UIViewTextView
로 보여준다.
extension StoryViewController: RestProcessorDelegate {
func didSucessWith(
data: Data,
response: URLResponse,
usage: ProjectURL) {
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
switch usage {
l case .getStory:
guard let decoded = try? JSONDecoder().decode(Story.self, from: data) else { return }
if let myURL = decoded.url,
let url = URL(string: myURL){
let myReqeust = URLRequest(url: url)
DispatchQueue.main.async {
self.webView.load(myReqeust)
self.addWebView()
}
}else if let text = decoded.text {
DispatchQueue.main.async {
self.textView.text = text
self.addTextView()
}
}
default:
break
}
}
func didFailwith(
error: Error?,
response: URLResponse?,
usage: ProjectURL) {
}
}
View 추가
WebView
와 UITextView
를 띄우기 위해서 뷰를 추가하고 오토레이아웃을 잡아준다.
func addWebView() {
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
webView.addSpinner()
}
func addTextView() {
view.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}