简体   繁体   中英

CollectionView data repeat in iOS Swift?

I have an API call to list tasks from the database. Now I can able to retrieve tasks and loaded in the collection view. When tap creates a new task button, I will fill the form and save it to the database. When going back to the task list it will hit API and list old tasks with new tasks. But, In my, it shows duplicate tasks too.

For Example:- My task array [task1, task2, task3] but the result [task1, task2, task3, task 3, task 1]

Here is my code for the API call.

  var filterID: String?
     @objc
   private func didPullToRefresh(_ sender: Any) {
    // Do you your api calls in here, and then asynchronously remember to stop the
    // refreshing when you've got a result (either positive or negative)

    DispatchQueue.main.async {

  //                self.collectionView.reloadData()
            self.refreshControl.endRefreshing()

        }

}

public override func viewDidAppear(_ animated: Bool) {



   //        apiCall()
    self.alamofireTaskList(filterID: filterID ?? "")

   //            SocketIOManager().connectSocket()
   //        SocketIOManager().recieve()
  }

 public override func viewWillAppear(_ animated: Bool) {

  //                self.collectionView.reloadData()

  //        self.alamofireTaskList(filterID: filterID ?? "")

  }



    public func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
        return "TaskListCollectionViewCell"
    }

    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            print("count::\(self.myTaskAry.count)")
            return self.myTaskAry.count
        }

  public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
         let inset:CGFloat = 10
         return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
     }

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: UIScreen.main.bounds.width, height: 80)
     }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TaskListCollectionViewCell", for: indexPath) as! TaskListCollectionViewCell

                cell.layer.cornerRadius = 10
                let shadowPath2 = UIBezierPath(rect: cell.bounds)
                cell.layer.masksToBounds = false
                cell.layer.shadowColor = UIColor(hexString: "#a8abbd")?.withAlphaComponent(0.3).cgColor
                cell.layer.shadowOffset = CGSize(width: CGFloat(0.0), height: CGFloat(5.0))

                cell.layer.shadowOpacity = 0.20
                cell.layer.shadowPath = shadowPath2.cgPath

         //   let sortedData = self.myTaskAry.sorted{ $0.created > $1.created }



           // let t = sortedData[indexPath.row]
        let t = self.myTaskAry[indexPath.row]

        print("t name::", t.name)
        print("t assignee:::", t.assignee)

            cell.tagName?.text = t.name

            cell.assigneeName?.text = t.name



        for val in (t._embedded?.variable)! {

            self.taskVariableValues.append(val)
            print("task variables::", val)

            if val.name == "loanAmount" {

                 print("t loanamount:::", val.value)

                       cell.variablevalue1.text = val.value
                   }

                   if val.name == "firstName" {

                     print("t firstname:::", val.value)

                       cell.variablevalue2.text = val.value
                   }
        }
        print("task variable array", self.taskVariableValues)


//        let taskVal = self.taskVariableValues[indexPath.row]


//
            let formato = DateFormatter()
            formato.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            formato.timeZone = NSTimeZone.local
            formato.formatterBehavior = .default
            let data = formato.date(from: t.created)
            formato.dateFormat = "dd-MM-yyyy"
//            print("data::\(String(describing: getPastTime(for: data!)))")

            cell.dateCreated?.text = getPastTime(for: data!)
            cell.tagName?.textColor = UIColor(hexString: "#00bdff")
            cell.tagView.backgroundColor = UIColor(hexString: "#00BDFF")?.withAlphaComponent(0.25)
//          t.processInstanceId
            print(t._embedded)
            return cell

        }


    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

//        let indexPath = collectionView.indexPathsForSelectedItems
//          let currentCell = collectionView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
        let sortedData = self.myTaskAry.sorted{ $0.created > $1.created }

        let t = sortedData[indexPath.row]
        print(t.processInstanceId)

         let str = t.formKey

          let result = String(str.dropFirst(7))
          print(result)
          let s = String(result.dropLast(10))
          print("newFormKey", s )


          let v = convap(text: s)


          let viewController = CreateCardViewController()
          navigationController?.setNavigationBarHidden(true, animated: false)
          tabBarController?.tabBar.isHidden = true
          viewController.hidesBottomBarWhenPushed = true
          viewController.processInstanceId = t.processInstanceId
          viewController.cardName = t.name
          viewController.TaskIdValue = t.id
          viewController.formKey = v
          viewController.tabName = "OpenTask"
          viewController.fullFormKey = t.formKey

          navigationController?.pushViewController(viewController, animated: true)
    }

    func convap (text : String) -> String {
                 return text.replacingOccurrences(of: ":", with: "/")
    }

    func alamofireTaskList(filterID: String) {


      print("after removing::", self.myTaskAry.count)

        let authToken = UserDefaults.standard.string(forKey: "authToken")
               let bearerToken: String = "Bearer " + (authToken ?? "")
               print("baearer token::\(bearerToken)")

        let headers:HTTPHeaders = ["Content-Type":"Application/json",
                       "Authorization": "Bearer " + (authToken ?? ""),
                       "Accept":"application/hal+json"]

      let newBaseURL = UserDefaults.standard.string(forKey: "baseURL")!
      let v = newBaseURL + "/engine-rest" + "/filter/\(filterID)/list"
      print("task list....", v)


      let id = processDefID


      let parameters : Parameters = [

        "sorting": [
            [

            "sortBy":"created",
            "sortOrder": "desc"

            ]
        ],
        "assigned" : true,
        "processDefinitionId": id ?? "",
        "processVariables": []

      ]

      print("parameters for task:::", parameters)

       AF.request(v , method: .post, parameters: parameters, encoding: JSONEncoding.default,
    headers: headers).responseJSON { (response:AFDataResponse) in

       //            print("task list response",response.result)

        switch response.result {
        case .success:
            if let data = response.data {
                // Convert This in JSON
                do {
                    let responseDecoded = try JSONDecoder().decode(Welcome.self, from: data)
                    print(" task list USER: ", responseDecoded._embedded.task, "Etc...")

        //                        self.myTaskAry = responseDecoded._embedded.task

                     self.myTaskAry.removeAll()
                    for task in responseDecoded._embedded.task {

                        self.myTaskAry.append(task)

                    }




                    print("myTask array:\(self.myTaskAry)")
                    print("myTask count:\(self.myTaskAry.count)")

                    DispatchQueue.main.async {
                        self.collectionView.reloadData()

                        self.view.hideSkeleton()
                    }



                }catch let error as NSError{
                    print(error)
                    self.view.hideSkeleton()

                }

            }
        case .failure(let error):
            print("Error:", error)
            self.view.hideSkeleton()

          }


          }
       }

Here is the screenshot:

在此处输入图像描述

在此处输入图像描述 在此处输入图像描述

Try to replace your method with this one

func alamofireTaskList(filterID: String) {


  print("after removing::", self.myTaskAry.count)

    let authToken = UserDefaults.standard.string(forKey: "authToken")
           let bearerToken: String = "Bearer " + (authToken ?? "")
           print("baearer token::\(bearerToken)")

    let headers:HTTPHeaders = ["Content-Type":"Application/json",
                   "Authorization": "Bearer " + (authToken ?? ""),
                   "Accept":"application/hal+json"]

  let newBaseURL = UserDefaults.standard.string(forKey: "baseURL")!
  let v = newBaseURL + "/engine-rest" + "/filter/\(filterID)/list"
  print("task list....", v)


  let id = processDefID


  let parameters : Parameters = [

    "sorting": [
        [

        "sortBy":"created",
        "sortOrder": "desc"

        ]
    ],
    "assigned" : true,
    "processDefinitionId": id ?? "",
    "processVariables": []

  ]

  print("parameters for task:::", parameters)

   AF.request(v , method: .post, parameters: parameters, encoding: JSONEncoding.default, 
headers: headers).responseJSON {[weak self] (response:AFDataResponse) in

   //            print("task list response",response.result)

    switch response.result {
    case .success:
        if let data = response.data {
            // Convert This in JSON
            do {
                let responseDecoded = try JSONDecoder().decode(Welcome.self, from: data)
                print(" task list USER: ", responseDecoded._embedded.task, "Etc...")

    //                        self?.myTaskAry = responseDecoded._embedded.task

                 self?.myTaskAry.removeAll()
                for task in responseDecoded._embedded.task {

                    self?.myTaskAry.append(task)

                }




                print("myTask array:\(self.myTaskAry)")
                print("myTask count:\(self.myTaskAry.count)")

                DispatchQueue.main.async {
                    self?.collectionView.reloadData()

                    self?.view.hideSkeleton()
                }



            }catch let error as NSError{
                print(error)
                self?.view.hideSkeleton()

            }

        }
    case .failure(let error):
        print("Error:", error)
        self?.view.hideSkeleton()

      }


      }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM