개발/Swift
Swift CollectionView Scroll 이미지로 인한 렉 현상 해결
덤벨로퍼
2021. 2. 22. 14:49
Modern Collection View 와 MVVM 패턴 가이드
[iOS] Modern Collection View & MVVM 패턴 가이드 - 인프런 | 강의
MVVM 패턴과 Modern Collection View를 사용해 네트워킹을 구현하고, 다양하고 동적인 Collection View를 자유자재로 다룰 수 있게 됩니다., Swift iOS UI, 제대로 다루는 핵심 기술! 📲 iOS Swift 레이아웃 구현을
www.inflearn.com
스크롤 할때마다 렉이걸려서 보니 스크롤 할때마다 Cell을 계속 생성하고있었음
그중 image를 url 로 가져오는 부분을 기다리느라 cell을 그리는게 늦어지는게 문제였다
이미지 set을 제거 한경우 스크롤이 빨랐음
해결 방법 -> 비동기로 image set 처리
URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, err) in
DispatchQueue.main.async {
if let data = data {
self.image = UIImage(data: data)
}
}
}.resume()
스크롤의 속도는 올라갔으나 스크롤을 내렸다가 다시 돌아왔을때
매번 이미지를 가져오려 fetch 해야하고 fetch 가 완료 되기 전까지
다른 인덱스의 이미지랑 꼬이는 현상이생김
해결 -> 캐시사용
class ImageCacheManager{
static let shared = NSCache<NSString, UIImage>()
private init (){}
}
let cacheKey = NSString(string: url)
if let cachedImage = ImageCacheManager.shared.object(forKey: cacheKey){
print("use cached Image")
self.image = cachedImage
return
}
URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, err) in
print("get Image from url")
DispatchQueue.main.async {
if let data = data , let image = UIImage(data: data){
ImageCacheManager.shared.setObject(image, forKey: cacheKey)
self.image = image
}
}
}.resume()
cache Image를 구현하여 사용하니 해당 문제 사라짐