[TIL] 식당 예약 어플 개발 - 5일차-

신승현·2024년 4월 29일

TIL

목록 보기
67/72
post-thumbnail

1️⃣ 검색 기능 수정

팀원이 검색화면과 기능을 구현하는 부분을 담당했는데, 아직 해결하지 못한 버그가 있었고, 구현하지 못한 기능으로 고생하고 계시길래 내가 도움을 드리기로 했다.

아직 구현이 안된 기능은 별점 기능이였다. 카카오 REST API로 받아오는 데이터에는 별점이 없기 때문에, 실제 어플을 개발한다면, 각 식당데이터에 별점을 주면서 데이터를 저장해야 할텐데, 이번 프로젝트는 그런 부분까지는 구현할 수 없기 때문에 랜덤으로 Double값을 15개 생성해서 Array에 담는 방식으로 하기로 했다.

// 랜덤 별점 생성
    func setStarArray() {
        for _ in 0...15 {
            let randomRating = Double.random(in: 3.5...5.0)
            starArray.append(randomRating)
        }
    }
    
    // 별점순으로 정렬
    func setRateSorted() {
        
        let combined = zip(self.starArray, self.result2)

        // 튜플 배열을 숫자에 따라 내림차순으로 정렬합니다.
        let sortedCombined = combined.sorted(by: { $0.0 > $1.0 })

        // 정렬된 배열에서 데이터 배열과 숫자 배열을 다시 추출합니다.
        self.starArray = sortedCombined.map { $0.0 }
        self.result2 = sortedCombined.map { $0.1 }

    }

별점순으로 정렬하는 방법은 Zip2Sequence타입으로 병합하고, 거기서 sorted함수를 사용해서 별점순으로 정렬해줬다.

그리고 별점을 출력해줄때는 소수 첫째자리까지만 출력해줘야 하기 때문에, String(format: "%.1f", starArray[indexPath.row])로 작성해줬다.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if isCollectionMode == true {
            guard let cell = searchCollectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as? CollectionViewCell else {
                return UICollectionViewCell()
            }
            cell.setCell(result2[indexPath.row])
            return cell
        }
        else {
            guard let cell = searchCollectionView.dequeueReusableCell(withReuseIdentifier: "ListCell", for: indexPath) as? ListCell else {
                return UICollectionViewCell()
            }
            cell.setCell(result2[indexPath.row])
            cell.ratingLabel.text = String(format: "%.1f", starArray[indexPath.row])
            
            return cell
        }
    }

버그 내용은 키보드에서 검색 버튼을 눌러도 검색이 되지 않는 부분이였다.
이 부분은 당일날 바로 해결하지 못하고 주말동안 시간을 조금씩 투자해가면서 고쳤다. 문제점은 코드상으로는 문제가 없었지만 다른 문제 때문에 검색결과가 나오지 않았다.

식당의 정보를 받아오는게 비동기 방식이였기 때문에 검색어가 입력되는 순간 이미 데이터를 받아와서 원하는 검색어 전의 검색어 데이터가 받아와지는 현상이였다. 그래서 비동기 방식에 타이머를 줘서 바로바로 검색이 되지 않게끔 수정했더니 원하던 결과를 얻을 수 있었다.

func updateSearchResults(for searchController: UISearchController) {
        dump(searchController.searchBar.text) // 디버깅을 위한 출력
                
        guard let text = searchController.searchBar.text?.lowercased() else {
            return
        }
        
        performSearch(with: text)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder() // 키보드를 숨깁니다.
        
        guard let text = searchBar.text?.lowercased() else {
            return
        }
        
        performSearch(with: text)
    }
    
    func performSearch(with text: String) {
        searchDebounceTimer?.invalidate()  // 기존 타이머를 취소합니다.
        searchDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { [weak self] _ in
            self?.networkManager.searchRestaurantList(keyword: text) { result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let a):
                        self?.result2 = a
                        self?.collectionView.reloadData()
                    case .failure(_):
                        // 에러 처리
                        break
                    }
                }
            }
            
            self?.isCollectionMode = true
            self?.setCollectionView()
        })
    }
profile
개발자

0개의 댓글