Ячейки представления коллекции продолжают увеличиваться в два раза от текущего числа массивов - PullRequest
0 голосов
/ 30 апреля 2018

Привет! Я использую метод модели данных для загрузки данных в ячейки collectionView. Выборка данных успешна, но когда я перехожу к другому viewController и возвращаюсь к текущему viewController, ячейки увеличиваются в два раза по сравнению с текущим счетчиком массива.

Я знаю, что метод, который я использовал, не идеален, потому что я новичок в Swift и получил их от Google. Как правильно справиться с этим?

API CALL

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
    }

Ответы [ 2 ]

0 голосов
/ 30 апреля 2018

Замените вашу функцию на эту.

Перед добавлением необходимо удалить все элементы из категорий массива.

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 = []
            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)
        }
    }
0 голосов
/ 30 апреля 2018

Пожалуйста, напишите код перед добавлением в массив.

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)
            }
        }

у вас есть вызов веб-службы в методе viewWillAppear. Поэтому, когда вы возвращаетесь из другого контроллера представления, он добавляет данные в тот же существующий массив. Так что, написание кода выше удалит существующие данные из массива.

или другое, что вы можете сделать, это вызвать веб-сервис в viewDidLoad метод.

Надеюсь, это поможет вам.

...