Swift3 프로그래밍을 처음 접했고 스위프트 2.2에서 기존 응용 프로그램을 스위프트 3으로 리팩터링하려고 시도했습니다. Alamofire
에 새 라이브러리 AlamofireImage
이 있습니다.스위프트에서 AlamofireImage로 리팩토링 3
그 라이브러리에는 imageCache가 있으며 현재 imageCache 코드를 리팩터링해야하는지 고려 중입니다. 내 질문은 그것이 현재의 구현에 비해 큰 이점이나 효율성을 가지고 있는가? 그렇다면 무엇인가? 이 코드를 개선하기위한 다른 제안도 환영받을 것입니다.
let imageCache = AutoPurgingImageCache()
은 훨씬 간단하고 읽기 쉬운 구현으로 보입니다.
다음은 현재 imageCache입니다.
class ShoppingManager {
static let sharedManager = ShoppingManager()
let imageCache = NSCache<AnyObject, AnyObject>()
여기 이미지를로드하고 캐시하는 원래 Swift 2 코드가 있습니다.
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ProductsCollectionViewCell
// Configure the cell
cell.lblProduct.text = ""
cell.backgroundColor = UIColor.white
cell.imgProduct.image = nil
//load Cell Image
let shopItem = shopItems[indexPath.row]
cell.alamoFireRequest?.cancel()
if let image = ShoppingManager.sharedManager.imageCache.object(forKey: shopItem.imgUrl! as AnyObject) as? UIImage {
cell.imgProduct.image = image
} else {
cell.alamoFireRequest = Alamofire.request(.GET, shopItem.imgUrl!).response(completionHandler: { (_, _, data: Data?, error: NSError?) -> Void in
if error == nil && data != nil {
let img = UIImage(data: data!)
cell.imgProduct.image = img
ShoppingManager.sharedManager.imageCache.setObject(img!, forKey: shopItem.imgUrl!)
}
})
}
return cell
}
여기 제가 지금 리팩토링 한 Swift3 코드입니다.
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ProductsCollectionViewCell
// Configure the cell
cell.lblProduct.text = ""
cell.backgroundColor = UIColor.white
cell.imgProduct.image = nil
//load Cell Image
let shopItem = shopItems[indexPath.row]
cell.alamoFireRequest?.cancel()
if let image = ShoppingManager.sharedManager.imageCache.object(forKey: shopItem.imgUrl! as AnyObject) as? UIImage {
cell.imgProduct.image = image
} else {
cell.alamoFireRequest = Alamofire.request(shopItem.imgUrl!).responseImage { response in
guard let img = response.result.value else {
// Handle error
return
}
cell.imgProduct.image = img
ShoppingManager.sharedManager.imageCache.setObject(img, forKey: shopItem.imgUrl! as AnyObject)
}
}
return cell
}
예, 감사합니다. 나는 그것이 쉽다는 것을 이해한다. 캐시는 현재 NSCache로 구현되어 있으며 캐시를 AlamofieImage 캐시로 변경해야하는 이유가 있는지 궁금합니다. – markhorrocks
내가 알게 된 것은 Alamofire를 따라 가야하고 wrapper가 완전히 있어야한다는 것입니다. 그렇지 않으면 Alamofire (AFNetworking과 유사)를 사용하지 마십시오. 믹싱 문제로 인해 복잡성과 디버깅 문제가 발생합니다. –