Swift3 在Swift 3中重构AlamofireImage
我是Swift3编程新手,已经接管并尝试将现有应用程序从SWIFT2.2重构为Swift3。我看到Swift3 在Swift 3中重构AlamofireImage,swift3,alamofire,Swift3,Alamofire,我是Swift3编程新手,已经接管并尝试将现有应用程序从SWIFT2.2重构为Swift3。我看到Alamofire有一个新的库AlamofireImage 在这个库中,我看到有一个imageCache,我正在考虑是否应该重构当前的imageCache代码来使用它。我的问题是,与当前的实现相比,它是否具有主要的优势或效率?如果是,它们是什么?如有任何其他改进本规范的建议,也将不胜感激 让imageCache=AutoPurgingImageCache()看起来是一个更简单、可读性更强的实现 这是
Alamofire
有一个新的库AlamofireImage
在这个库中,我看到有一个imageCache,我正在考虑是否应该重构当前的imageCache代码来使用它。我的问题是,与当前的实现相比,它是否具有主要的优势或效率?如果是,它们是什么?如有任何其他改进本规范的建议,也将不胜感激
让imageCache=AutoPurgingImageCache()
看起来是一个更简单、可读性更强的实现
这是当前的imageCache
class ShoppingManager {
static let sharedManager = ShoppingManager()
let imageCache = NSCache<AnyObject, AnyObject>()
下面是我重构到现在的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
}
你检查过他们的样本代码了吗 根据示例代码,这非常简单:
imageView.af_setImage(
withURL: URL(string: URLString)!,
placeholderImage: placeholderImage,
filter: AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: 20.0),
imageTransition: .crossDissolve(0.2)
)
imageView.af_cancelImageRequest()
参考:
或签出AlamofireImageView:
public func af_setImage
此方法支持缓存。是的,谢谢。我知道这很容易。缓存目前实现为NSCache,我想知道是否有充分的理由将缓存更改为AlamofieMage缓存。我发现,要么我们应该完全遵循Alamofire及其包装器,要么不要使用Alamofire(与AFNetworking类似)。问题是混合会造成复杂性和调试问题。
imageView.af_setImage(
withURL: URL(string: URLString)!,
placeholderImage: placeholderImage,
filter: AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: 20.0),
imageTransition: .crossDissolve(0.2)
)
imageView.af_cancelImageRequest()