当视图加载时,我从api调用填充数据并将其显示到单元格:
override func viewDidLoad() {
super.viewDidLoad()
parseData(urll: url)
}
当我使用搜索栏进行搜索时,我正在使用以下代码填充一组新的项目:
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)
}
但是,当它加载新项目时,不会删除旧项目,我尝试使用重新加载数据,但是它没有用。
我在
parseData()
函数中具有重载数据功能。parsedata()
代码: 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!
}
最佳答案
不会删除旧项,因为您要将搜索中的图像URL附加到现有的imageUrlArray属性中。因此,您可以在发出搜索请求之前删除该数组中的所有项目。只需将此行添加到parsedata()
函数的顶部即可:
self.imageUrlArray.removeAll(keepingCapacity: false)