[英]CollectionView data repeat in iOS Swift?
我有一個 API 調用來列出數據庫中的任務。 現在我可以檢索任務並加載到集合視圖中。 當點擊創建一個新的任務按鈕時,我將填寫表格並將其保存到數據庫中。 返回任務列表時,它將點擊 API 並列出舊任務和新任務。 但是,在我看來,它也顯示了重復的任務。
例如:- 我的任務數組 [task1, task2, task3] 但結果 [task1, task2, task3, task 3, task 1]
這是我的 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()
}
}
}
這是屏幕截圖:
嘗試用這個替換你的方法
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()
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.