嗨,我正在使用数据模型方法将数据加载到collectionView单元格中。数据获取成功,但当我导航到另一个viewController并返回到当前viewController时,单元格将增加当前数组计数的两倍。
我知道我使用的方法并不完美,因为我是新来的斯威夫特和我从谷歌得到的。处理这个问题的正确方法是什么?
API调用

func postToGetMyCoach()
    {
        let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
        var param : [String : AnyObject] = [:]

        param = ["apiKey": apiKey as AnyObject]
        print(param)
        Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in

            if (response.result.value != nil)
            {
               if let value = response.result.value
               {
                let json = JSON(value)
                //  let responseDictionary = json.dictionaryValue as [String: AnyObject]
              //  print("json:\(json)")

                /**** Category Array exctraction *****/
                let categoryArray = json["data"]["categories"].arrayValue
                print("Category Array:\(categoryArray)")

                for var mCategory in categoryArray
                {
                    let title = mCategory["title"].stringValue
                    let imageURL = mCategory["image"].stringValue
                    let id = mCategory["id"].stringValue

                    //Escape image url additional Charectors
                    self.cimageURL = imageURL.replacingOccurrences(of: "\\", with: "")
                    print("ESCAPED IMAGE URL\(self.cimageURL)")

                //    let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
                    let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)

                    self.categories.append(mcCategory)

                }
                self.collectionView.reloadData()

               }
            }
            else
            {
                print("No Response!",response)
            }
        }

集合视图委托
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCoachCCell", for: indexPath)
            as! MyCoachCCell

       // cell.activitiesImg.image = collectionViewImageArray[indexPath.row]
        let mCategories = categories[indexPath.row]
        cell.className.text = mCategories.title
     //   cell.classThumb.image = collectionViewImageArray[indexPath.row]

        // fetching image
        let mcImageURL = mCategories.imageURL
        Alamofire.request(mcImageURL).responseData(completionHandler: { response in
            //   debugPrint(response)
            //   debugPrint(response.result)
            if let image1 = response.result.value {
                self.imagefinal = UIImage(data: image1)!
                cell.classThumb.image = self.imagefinal
                print("IMG", self.imagefinal! )

            }
        })

        return cell
    }

最佳答案

请在追加到数组之前编写代码。

self.categories.removeAll()

在函数中,在开始for循环之前添加这一行。
func postToGetMyCoach()
    {
        let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
        var param : [String : AnyObject] = [:]

        param = ["apiKey": apiKey as AnyObject]
        print(param)
        Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in

            if (response.result.value != nil)
            {
               if let value = response.result.value
               {
                let json = JSON(value)
                //  let responseDictionary = json.dictionaryValue as [String: AnyObject]
              //  print("json:\(json)")

                /**** Category Array exctraction *****/
                let categoryArray = json["data"]["categories"].arrayValue
                print("Category Array:\(categoryArray)")

                self.categories.removeAll()
                for var mCategory in categoryArray
                {
                    let title = mCategory["title"].stringValue
                    let imageURL = mCategory["image"].stringValue
                    let id = mCategory["id"].stringValue

                    //Escape image url additional Charectors
                    self.cimageURL = imageURL.replacingOccurrences(of: "\\", with: "")
                    print("ESCAPED IMAGE URL\(self.cimageURL)")

                //    let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
                    let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)

                    self.categories.append(mcCategory)

                }
                self.collectionView.reloadData()

               }
            }
            else
            {
                print("No Response!",response)
            }
        }

您已经调用了VIEW WALW出现方法中的WebService。因此,每当您从另一个视图控制器返回时,它将在相同的现有数组中追加数据。因此,编写上面的代码将从数组中删除现有数据。
或者您可以在viewDidLoad方法中调用webservice。
希望这对你有帮助。

10-08 08:27
查看更多