如何快速过滤来自API的数据并显示在TableView上?

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

我正在尝试从 Finnhub 接收 API 数据并将其放入表视图中。

我使用的API数据是Symbol Lookup,这是一个接收公司详细名称和股票代码的API。

获取全球所有公司名称的是API数据,我想只过滤与美国相关的公司股票,并将其分配给表格视图。只有美国相关公司。

如何过滤来自API的数据并显示在TableView上?

这是我的代码

enum CompanyDataNetworkError: Error {
    case networkingError
    case dataError
    case parseError
}


final class CompanyDataManager {
    

    static let shared = CompanyDataManager()

    private init() {}
    
    
    typealias NetworkCompletion = (Result<[CompanyDataResult], CompanyDataNetworkError>) -> Void

  
    func fetchNetwork(searchTerm: String, completion: @escaping NetworkCompletion) {
        
        let myAPIKey = "myAPIKey"
        let urlString = "https://finnhub.io/api/v1/search?q=\(searchTerm)&token=\(myAPIKey)"
        print(urlString)
        
        performRequest(with: urlString) { result in
            completion(result)
        }
        
    }
    

    private func performRequest(with urlString: String, completion: @escaping NetworkCompletion) {
        //print(#function)
        guard let url = URL(string: urlString) else { return }
        
        let session = URLSession(configuration: .default)
        
        let task = session.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
                completion(.failure(.networkingError))
                print("DEBUG: Network Error")
                return
            }
            
            guard let safeData = data else {
                completion(.failure(.dataError))
                print("DEBUG: Data Error")
                return
            }
            

            if let company = self.parseJSON(safeData) {
                print("Parse Success")
                completion(.success(company))
            } else {
                print("DEBUG: Parse Failure")
                completion(.failure(.parseError))
            }
        }
        task.resume()
    }
    

    private func parseJSON(_ companyData: Data) -> [CompanyDataResult]? {
        print(#function)
    

        do {
            let companyData = try JSONDecoder().decode(CompanyData.self, from: companyData)
            return companyData.result
        } catch {
            print(error.localizedDescription)
            print("DEBUG: JSON Error")
            return nil
        }
    }
}

import UIKit

class SearchResultHomeController: UIViewController {

    
    var companyManager = CompanyDataManager.shared
    

    var searchTerm: String? {
        didSet {
            setupDatas()
        }
    }
    
    
    
    var companyArray: [CompanyDataResult] = []
    
    
    let tableView = UITableView()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        
    }
    
   

    }
    
    
    func setupDatas() {
        
        guard let term = searchTerm else { return }
        
        companyManager.fetchNetwork(searchTerm: term) { result in
            switch result {
            case .success(let companyDatas):

                self.companyArray = companyDatas

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
       
        
    }
    
}


extension SearchResultHomeController: UITableViewDataSource {
 
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return companyArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SearchResultCell", for: indexPath) as! SearchResultCell
        

        cell.selectionStyle = .none
        cell.textLabel?.text = companyArray[indexPath.row].codeName
        cell.detailTextLabel?.text = companyArray[indexPath.row].detailName
        
        
        return cell
        
    }
    
    
}

extension SearchResultHomeController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let eachStockDetailVC = EachStockDetailController()
        eachStockDetailVC.searchTerm = companyArray[indexPath.row].codeName
        present(eachStockDetailVC, animated: true)
    }
    
    
}

我试过 if error.localizedDescription == "The data couldn't be read because it is not in the correct format."如果它是错误的 api,使其不包含在 tableview 中,但它没有成功。谁能帮帮我...?

json swift api filter tableview
1个回答
0
投票

您可以使用过滤器只获取美国公司。例如试试这个代码:

func setupDatas() {

    guard let term = searchTerm else { return }

    companyManager.fetchNetwork(searchTerm: term) { result in
        switch result {
            case .success(let companyDatas):

                self.companyArray = companyDatas.filter { company in
                    company.codeName.contains("US")
                }

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            case .failure(let error):
                print(error.localizedDescription)
        }
    }


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