iOS Swift中CollectionView数据重复?

问题描述 投票:0回答:1

我有一个API调用来从数据库中列出任务。现在我可以检索任务并加载到集合视图中。当点击创建一个新的任务按钮时,我会填写表格并将其保存到数据库中。当回到任务列表时,它将点击API并将旧任务与新任务一起列出。但是,在我这里,它也会显示重复的任务。

例如:- 我的任务数组[task1, task2, task3],但结果[task1, task2, task3, task3, task1]。

这是我调用API的代码。

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

          }


          }
       }

下面是截图。

enter image description here

enter image description here enter image description here

ios arrays swift xcode uicollectionview
1个回答
1
投票

试着用这个方法替换你的方法

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

      }


      }
   }
© www.soinside.com 2019 - 2024. All rights reserved.