Skip to content

Commit

Permalink
[#91] SearchBar와 Pagination 연계 실습
Browse files Browse the repository at this point in the history
  • Loading branch information
Taehyeon-Kim committed Aug 4, 2022
1 parent 70caa6b commit 249e1c8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
12 changes: 10 additions & 2 deletions NetworkBasic/NetworkBasic/Base.lproj/Main.storyboard
Expand Up @@ -438,7 +438,7 @@
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="tiY-hL-gUl">
<rect key="frame" x="0.0" y="44" width="414" height="818"/>
<rect key="frame" x="0.0" y="95" width="414" height="767"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="5M3-Oq-fdv">
<size key="itemSize" width="263" height="275"/>
Expand Down Expand Up @@ -472,18 +472,26 @@
</collectionViewCell>
</cells>
</collectionView>
<searchBar contentMode="redraw" translatesAutoresizingMaskIntoConstraints="NO" id="Lav-GQ-1FD">
<rect key="frame" x="0.0" y="44" width="414" height="51"/>
<textInputTraits key="textInputTraits"/>
</searchBar>
</subviews>
<viewLayoutGuide key="safeArea" id="oFB-x5-Kvi"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="tiY-hL-gUl" firstAttribute="leading" secondItem="oFB-x5-Kvi" secondAttribute="leading" id="FgX-Nt-8Dj"/>
<constraint firstItem="tiY-hL-gUl" firstAttribute="top" secondItem="Lav-GQ-1FD" secondAttribute="bottom" id="Vo6-ZG-YOm"/>
<constraint firstItem="Lav-GQ-1FD" firstAttribute="leading" secondItem="oFB-x5-Kvi" secondAttribute="leading" id="Wtx-N4-GBb"/>
<constraint firstItem="oFB-x5-Kvi" firstAttribute="bottom" secondItem="tiY-hL-gUl" secondAttribute="bottom" id="YZD-cH-exS"/>
<constraint firstItem="tiY-hL-gUl" firstAttribute="top" secondItem="oFB-x5-Kvi" secondAttribute="top" id="Zfd-9w-2Z4"/>
<constraint firstItem="Lav-GQ-1FD" firstAttribute="trailing" secondItem="oFB-x5-Kvi" secondAttribute="trailing" id="gf8-2Z-ZA4"/>
<constraint firstItem="oFB-x5-Kvi" firstAttribute="trailing" secondItem="tiY-hL-gUl" secondAttribute="trailing" id="tLM-Ch-AcM"/>
<constraint firstItem="Lav-GQ-1FD" firstAttribute="top" secondItem="oFB-x5-Kvi" secondAttribute="top" id="vIq-an-Pfj"/>
</constraints>
</view>
<connections>
<outlet property="collectionView" destination="tiY-hL-gUl" id="KN2-ZZ-Dn3"/>
<outlet property="searchBar" destination="Lav-GQ-1FD" id="r6H-bj-hKy"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="PAw-DM-cSj" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
Expand Down
41 changes: 36 additions & 5 deletions NetworkBasic/NetworkBasic/ImageSearchViewController.swift
Expand Up @@ -17,16 +17,17 @@ class ImageSearchViewController: UIViewController {
var totalCount = 0

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var searchBar: UISearchBar!

override func viewDidLoad() {
super.viewDidLoad()
fetchImage()
searchBar.delegate = self
configureCollectionView()
}

// fetchImage, requestImage, callRequestImage, getImage -> response에 따라 네이밍을 설정해주기도 함.
func fetchImage() {
let text = "클클클".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
func fetchImage(query: String) {
let text = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = EndPoint.imageSearchURL + "query=\(text)&display=100&start=\(startPage)"
let headers: HTTPHeaders = [
"X-Naver-Client-Id": APIKey.NAVER_ID,
Expand All @@ -35,7 +36,7 @@ class ImageSearchViewController: UIViewController {

AF.request(url, method: .get, headers: headers)
.validate(statusCode: 200...500)
.responseJSON { response in
.responseData { response in
switch response.result {
case .success(let value):
let json = JSON(value)
Expand All @@ -54,6 +55,36 @@ class ImageSearchViewController: UIViewController {
}
}

extension ImageSearchViewController: UISearchBarDelegate {

// 검색 버튼 클릭 시 실행. (키보드 Return키에 디폴트 구현)
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

if let text = searchBar.text {
// 검색 결과가 계속 바뀌기 때문에, 그럴 때마다 초기화 해줄 필요가 있음
searchThumnailStrings.removeAll()
startPage = 1
collectionView.scrollsToTop = true
fetchImage(query: text)
}

view.endEditing(true)
}

// 취소 버튼 눌렀을 때 실행
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchThumnailStrings.removeAll()
collectionView.reloadData()
searchBar.text = ""
searchBar.setShowsCancelButton(false, animated: true)
}

// 서치바에 커서가 깜빡이기 시작할 때 실행
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
}

extension ImageSearchViewController: UICollectionViewDelegate, UICollectionViewDataSource {
private func configureCollectionView() {
collectionView.delegate = self
Expand Down Expand Up @@ -105,7 +136,7 @@ extension ImageSearchViewController: UICollectionViewDataSourcePrefetching {
for indexPath in indexPaths {
if searchThumnailStrings.indices.last == indexPath.item && searchThumnailStrings.count < totalCount {
startPage += 30
fetchImage()
fetchImage(query: searchBar.text!)
}
}
// print("===\(indexPaths)")
Expand Down

0 comments on commit 249e1c8

Please sign in to comment.