微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从api过滤相同类型的数据并显示在表视图上

如何解决从api过滤相同类型的数据并显示在表视图上

(https://jsonplaceholder.typicode.com/posts) 这是我的 API 响应 (关注userId和id)-

    [
      {
        "userId": 1,"id": 1,"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      },{
        "userId": 1,"id": 2,"title": "qui est esse","body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
      },{
        "userId": 2,"id": 3,"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut","body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
      },.
    .
    .
    .
      {
    "userId": 10,"id": 100,"title": "at nam consequatur ea labore ea harum","body": "cupiditate quo est a modi nesciunt soluta\nipsa voluptas error itaque dicta in\nautem qui minus magnam et distinctio eum\naccusamus ratione error aut"
  }
    ]

我从 API 中两次获得 UserID - 1,但我只能在 TableViewCell 上显示它一次...当我点击 userID - 1 的 Cell 时,我必须显示 userID- 1 的相应数据,即("id": 1 and "id": 2) 在 AllDataViewController 的 TableView 上,即。(NextViewController).

下面是我的编码部分,无需过滤数据即可正常工作

视图控制器 -

import UIKit
import Alamofire

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
    @IBOutlet weak var table:UITableView!
    var listArray = [Post]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        table.dataSource = self
        table.delegate = self
    }
}
  
extension ViewController{
    // MARK:- TableView Code
    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        
        return listArray.count
    }
     
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let mycell=UITableViewCell(style: UITableViewCell.CellStyle.subtitle,reuseIdentifier: nil)
        mycell.detailTextLabel!.text = String(listArray[indexPath.row].userId)
       return mycell
    }
    
    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        //need code for this method
    }
}

// MARK:- API Calling
extension ViewController{
    // MARK: - Modals
    struct Post:Codable {
        var userId: Int
        var id:Int
        var title:String
        var body:String
    }

    func loadData()
    {
        let strURL = "https://jsonplaceholder.typicode.com/posts"
        
        AF.request(strURL,method: .get,encoding: JSONEncoding.default).responseJSON { (response) in
            
            switch response.result
            {
            case.success:
                print(response)
                dispatchQueue.main.async(execute: { [self] in
                    
                    if let result = response.data{
                        do
                        {
                            let jsonDecoder = JSONDecoder()
                            let decodedData = try jsonDecoder.decode([Post].self,from: result)
                            let decoderesult = decodedData
                            self.listArray.append(contentsOf: decoderesult)
                            self.table.reloadData()
                        }
        catch {
            print("Error:",error)
        }
                    }
                  })
                break
            case.failure(let err):
                print("error->",err)
            }
        }
    }
}

AllDataViewController -

import UIKit

class AllDataViewController: UIViewController,UITableViewDataSource {
    
    @IBOutlet weak var allDataTable: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
}

extension AllDataViewController{
    // MARK:- TableView Code
    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return 10
    }
     
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        //need code for this method
        
        let mycell=UITableViewCell(style: UITableViewCell.CellStyle.subtitle,reuseIdentifier: nil)
//        mycell.detailTextLabel!.text = ???
//        mycell.textLabel!.text = ???
       return mycell
    }
}

(1) 如何在本地过滤API数据,并在用户ID对应的AllDataViewController上显示数据??

MY PROJECT LOOK LIKE THIS BY USING ABOVE CODE

THIS IS HOW I NEED MY PROJECT TO LOOK LIKE

解决方法

以下是您需要的工作代码。我没有实现任何架构,所以大部分代码都在 ViewController 中以供您理解。我希望您可以使用 StoryBoard 创建简单的 tableView 设计并测试代码。

注意-:我有一个从 VC1 的 tableView 单元到故事板中的 VC2 的 segue。

VC1-:

  import UIKit

class TestController: UIViewController {
    
    @IBOutlet weak var testTableView: UITableView!
    private var filteredData:[User]? = []
    private var selectedUserId:Int?
    
    var UserObjects:[User]?{
        didSet{
            sortedUsers(UserObjects!)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getData {  user,error in
            if error == nil{
                self.UserObjects = user!
                
            }
        }
    }
    
    func sortedUsers(_ array:[User]) {
        DispatchQueue.global(qos: .default).async { [unowned self] in
            let sortedList = array.sorted(by: {$0.userId < $1.userId})
            self.getSingleObjectForUsres(sortedList)
        }
    }
    
    func getSingleObjectForUsres(_ sortedArray:[User]) {
        filteredData?.append(sortedArray[0])
        
        DispatchQueue.global(qos: .default).async { [unowned self] in
            for index in 1..<sortedArray.count{
                if sortedArray[index].userId != sortedArray[index - 1].userId{
                    self.filteredData?.append(sortedArray[index])
                }
            }
            DispatchQueue.main.async {
                self.testTableView.reloadData()
            }
        }
    }
    
}

extension TestController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        guard let filteredData = filteredData else{
            return 0
        }
        return filteredData.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TestTableCell
        cell.eventLabel.text = filteredData![indexPath.row].userId.description
        return cell
    }
    
    func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView,willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        selectedUserId = filteredData![indexPath.row].userId
        return indexPath
    }
    
}

extension TestController{
    override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
        let destinationVC = segue.destination as? TestControllerTwo
        guard let users = UserObjects else{
            return
        }
        destinationVC?.userObjects = users
        destinationVC!.selectedUserObjects = selectedUserId!
    }
}

extension TestController{
    var session:URLSession?{
        URLSession.shared
    }
    func getData(completion:
                    @escaping ([User]?,Error?) -> Void)  {
        let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
        let task = session!.dataTask(with: url) {  data,response,error in
            //guard let self = self else { return }
            guard let response = response as? HTTPURLResponse,response.statusCode == 200,error == nil,let data = data else {
                completion(nil,error)
                return
            }
            let decoder = JSONDecoder()
            do {
                let users = try decoder.decode([User].self,from: data)
                completion(users,nil)
            } catch let error{
                print(error)
            }
        }
        task.resume()
        
    }
}

struct User:Decodable,Hashable{
    
    var userId:Int
    var id:Int
    var title:String
    var body:String
    
    init(userId:Int,id:Int,title:String,body:String) {
        self.userId = userId
        self.id = id
        self.title = title
        self.body = body
    }
    
    static func == (lhs: User,rhs: User) -> Bool {
        lhs.id == rhs.id
    }
    
}

VC2-:

import UIKit

class TestControllerTwo: UIViewController {
    
    @IBOutlet weak var testTableView2: UITableView!
    var userObjects:[User] = []
    var selectedUserObjects:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        filterUsers()
    }
    
    func filterUsers(){
        userObjects = userObjects.filter{$0.userId == selectedUserObjects}
        testTableView2.reloadData()
    }
    
    @IBAction func addEventAndPop(_ sender: Any) {
        navigationController?.popViewController(animated: true)
    }
    
}

extension TestControllerTwo:UITableViewDelegate,numberOfRowsInSection section: Int) -> Int {
        return userObjects.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
        cell?.textLabel!.text = userObjects[indexPath.row].id.description
        return cell!
    }
    
    func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
}

输出-:

enter image description hereenter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。