[TIL] 09.01

Junyoung_Hong·2023년 9월 1일
0

TIL_9월

목록 보기
1/19
post-thumbnail

1. UIRefreshControl 이용해서 새로고침

평소에 사용하는 다양한 앱에서 사용하는 기능인 '화면을 당겨서 새로고침' 은 UIRefreshControl클래스를 이용해서 구현할 수 있다. 이 클래스는 화면을 당기기 때문에 UIScrollView 클래스를 포함해서 이 클래스를 상속받는 UITableView, UICollectionView 에서 사용할 수 있다.

1-1. UIRefreshControl 인스턴스 생성

let refreshControl = UIRefreshControl()

1-2. 기본 설정

생성한 인스턴스에 action 함수를 추가하고, 상태는 꼭 .valueChanged 를 입력해야 한다.

private func configureRefreshControl() {
    refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        
    // CollectionView에 refreshControl 추가
    photoCollectionView.refreshControl = refreshControl
        
    refreshControl.tintColor = UIColor(named: "CheckColor")
    refreshControl.attributedTitle = NSAttributedString(string: "당겨서 새로고침", attributes: [.foregroundColor: UIColor(named: "CheckColor")!])
}

1-3. 새로 데이터 불러오는 함수 구현

@objc private func refreshData() {
    // API 호출 및 데이터 업데이트 로직을 구현
    fetchNewData()
}
    
private func fetchNewData() {
    let imageURLString = "https://api.thecatapi.com/v1/images/search?limit=10"
        
    URLSession.shared.dataTask(with: URL(string: imageURLString)!) { data, response, error in
        if let error = error {
            print("Error fetching data: \(error)")
            return
        }
            
        guard let data = data else {
            print("No data received")
            return
        }
            
        do {
            _ = try JSONDecoder().decode([CatImage].self, from: data)
                
            // 0.7초 딜레이
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
                    
                // 새로운 이미지 데이터로 collectionView 갱신
                self.photoCollectionView.reloadData()
                    
                // 새로고침 작업 완료 후, 호출
                self.refreshControl.endRefreshing()
            }
        } catch {
            print("Error decoding JSON: \(error)")
        }
    }.resume()
}
profile
iOS 개발자를 향해 성장 중

0개의 댓글