【发布时间】:2020-07-19 01:45:43
【问题描述】:
我希望搜索栏返回数组中每个对象的标题。我相信问题出在我的 for 循环中,但我不确定。希望你们能告诉我我做错了什么。
我正在通过 API 进行搜索。这是我试图搜索的数组
struct ProductResponse: Decodable {
let results: [SearchResults]
}
struct SearchResults: Decodable {
let title: String
let id:Int
}
我创建了一个 for 循环来遍历数组中的每个对象并获取标题和 ID。
func fetchProduct(productName: String) {
let urlString = "\(searchURL)&query=\(productName)&number=25"
performRequest(urlString: urlString)
}
func performRequest(urlString: String) {
// Create a URL
if let url = URL(string: urlString) {
//Create a URLSession
let session = URLSession(configuration: .default)
// Give the session a task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(productTitle: safeData)
}
}
// Start the task
task.resume()
}
}
func parseJSON(productTitle: Data) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(ProductResponse.self, from: productTitle)
print(decodedData.results)
} catch {
print(error)
}
}
}
我创建了这个函数来重新加载表格视图中的数据。当我在搜索栏中搜索产品结果时,我的 tableview 没有返回任何内容。目标是让我的 tableview 在 tableview 单元格中返回每个结果
var listOfProducts = [SearchResults]() {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
self.navigationItem.title = "\(self.listOfProducts.count) Products found"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
productSearch.delegate = self
}
func downloadJSON() {
guard let downloadURL = url else { fatalError("Failed to get URL")}
URLSession.shared.dataTask(with: downloadURL) { (data, Response, error) in
print("downloaded")
}.resume()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return listOfProducts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let product = listOfProducts[indexPath.row].title
cell.textLabel?.text = product
return cell
}
}
extension ProductsTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let searchBarText = searchBar.text {
searchRequest.fetchProduct(productName: searchBarText)
}
}
}
【问题讨论】:
-
嘿 Andrew,在 parseJSON 方法下,您应用了一个循环来获取每个对象的标题,但您能否确认在同一个函数变量“decodedData.results”下是否有值?如果是,该变量包含一个值,那么您为什么要使用 for 循环,因为我看到您使用了表格视图,您可以传递该变量并使用每个对象标题 using=> result[indexpath.row]?.title 在您的单元格上排在。
-
感谢@AshutoshkumarMishra。所以我打印出 decodedData.results 的结果并取回每个产品的标题和 id。我的问题现在我的表格视图单元格不显示标题。我得到的只是空白单元格。
-
因此,当您打印出 decodedData.results 的结果并以数组的形式获得结果时,然后将该数组分配给您的“listOfProducts”变量并重新加载表格视图。
-
嘿@AshutoshkumarMishra,由于某种原因,当ai打印出listOfProducts时,它不会返回任何内容。即使我将变量设置为 [SearchResults] 数组。我觉得我错过了一些简单的事情。
-
您好 Andrew,如果您在“decodedData.results”中有数据,那么它肯定会在重新加载表后分配给“listOfProducts”。
标签: json swift uitableview for-loop uisearchbardelegate