평소에 사용하는 다양한 앱에서 사용하는 기능인 '화면을 당겨서 새로고침' 은 UIRefreshControl클래스를 이용해서 구현할 수 있다. 이 클래스는 화면을 당기기 때문에 UIScrollView 클래스를 포함해서 이 클래스를 상속받는 UITableView, UICollectionView 에서 사용할 수 있다.
let refreshControl = UIRefreshControl()
생성한 인스턴스에 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")!])
}
@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()
}