iosswiftuicollectionviewuicollectionviewcell

Collection view cells refresh not happening


When view loads I am populating the data from an API call and displaying them to the cells:

override func viewDidLoad() {
    super.viewDidLoad()
    parseData(urll: url)
}

When I search from using a search bar I am populating a new set of items using this code:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

    let keywords = searchBar.text
    let finalKey =  keywords?.replacingOccurrences(of: " ", with: "+")
    let finalurl = "https://api.giphy.com/v1/gifs/search?api_key=0d4f9877de6d4927943adf5a0d20e8a0&q=\(finalKey!)&limit=25&offset=0&rating=G&lang=en"
    parseData(urll: finalurl)
          self.view.endEditing(true)
}

But when it's loading the new items the old items are not being removed, I've tried using reload data but it didn't work.

And I have reload data function in the parseData() function.

parsedata() code:

 func parseData(urll : String) {
    var request = URLRequest(url: URL(string: urll)!)
    request.httpMethod = "GET"
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config, delegate: nil, delegateQueue: .main)
    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
        }
        else {
            do {
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
                if  let gifArray = fetchedData.value(forKey: "data") as? NSArray {
                    if  let gifarrayImg = gifArray.value(forKey: "images") as? NSArray {
                        if let gifarrayImgFixedWdth = gifarrayImg.value(forKey: "fixed_width") as? NSArray {
                            for gif in gifarrayImgFixedWdth {
                                if let gifDict = gif as? NSDictionary {
                                    if let imgURL = gifDict.value(forKey: "url") {
                                        print(imgURL)
                                        self.imgUrlArray.append(imgURL as! String)
                                    }
                                    if let imgHeight = gifDict.value(forKey: "height") {
                                        self.height.append(imgHeight as! String)
                                        print(imgHeight)
                                    }
                                    DispatchQueue.main.async {
                                        self.collectionView.reloadData()
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch {
                print("Error2")
            }
        }
    }
    task.resume()
}

CollectviewdataSource

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imgUrlArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CollectionViewCell
    cell?.layer.shouldRasterize = true
    cell?.layer.rasterizationScale = UIScreen.main.scale

    let resource = ImageResource(downloadURL: URL(string : imgUrlArray[indexPath.row])!, cacheKey: imgUrlArray[indexPath.row])
    cell?.imgview.kf.setImage(with: resource)
    

    return cell!
}

Solution

  • The old items aren't being removed because you are appending the image URLs from the search to the existing imageUrlArray property. So you can remove all the items in that array before you make the search request. Just add this line to the top of your parsedata() function:

    self.imageUrlArray.removeAll(keepingCapacity: false)