I am new to swift I am trying to make a slider using UICollectionView which is working properly,
but when I try to implement cache (Kingfisher
) it doesn't show my images in slider
here is my implementation
extension CompanyViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(self.sliderModel != nil){
return (self.sliderModel?.data.count)!
}else{
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BannerCollectionViewCell
if(self.sliderModel != nil){
if(self.sliderModel.data.count == indexPath.row){
let url = URL(string:(self.sliderModel?.data[indexPath.row].experienceImage.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed ))!)
cell.sliderImageView.kf.setImage(with: url)
}else{
//cell.sliderImageView.image = self.imgArr[indexPath.row]
let url = URL(string:(self.sliderModel?.data[indexPath.row].experienceImage.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed ))!)
cell.sliderImageView.kf.setImage(with: url)
}
}
return cell
}
}
But Image is not visible in my slider, I checked my model I am getting the response from server and Images are there in image url. May be I am downloading the Image at wrong place.
This is how I am getting my jsondata and assigning it in my model
func getBannerData(){
dispatchGroup.enter()
let defaults = UserDefaults.standard
let appId = defaults.string(forKey: Constants.APPID)
let token = "Bearer "+defaults.string(forKey: Constants.TOKEN)!
if let url = URL(string: Constants.EXPERIENCE_BANNER_CENTER+appId!){
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(token, forHTTPHeaderField:"Authorization")
APIManager.sharedInstance.getCall(request: request){
(data) in
if(!data.isEmpty){
do{
self.sliderModel = try JSONDecoder().decode(SliderModel.self, from: Data(data.utf8))
DispatchQueue.main.async {
self.pageView.numberOfPages = (self.sliderModel?.data.count)!
self.sliderCollectionView.reloadData()
}
self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.changeImage), userInfo: nil, repeats: true)
self.stopActivityIndicator()
self.dispatchGroup.leave()
}
catch{
self.stopActivityIndicator()
self.showAlertMessage(alertMessage: Constants.COMMON_ERROR)
}
}
}
}
}
Can anyone please suggest what I am doing wrong
Any help would be appreciated
What you are doing is wrong. You cannot network directly in
cellForItem
. You can ask for the download to begin now if needed, sure, but you cannot keep a reference tocell
, because the user might scroll the cell out of view, and it might need to be reused, while the download is still taking place.Instead, you must download into your model and then reload the collection view.