这是我用来查找特定书籍的控制器。当我在搜索栏中键入内容时,在键入过程中或完成键入操作后,不会向我显示任何图书信息。我想了解原因并找到解决该问题的解决方案。

import UIKit

class TextbookSearchViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!

    var booksFound = [[String: AnyObject]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    func queryBooks(bookTitle: String) {
        let stringURL = "https://www.googleapis.com/books/v1/volumes?q=\(bookTitle)"
        guard let url = URL(string: stringURL) else {
            print("Problem with URL")
            return
        }
        let urlRequest = URLRequest(url: url as URL)
        let urlSession = URLSession.shared
        let queryTask = urlSession.dataTask(with: urlRequest) { (data, response, error) in
            guard let jsonData = data else {
                print("No Information could be Found:")
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]
                let tableItems = json["Items"] as! [[String: AnyObject]]
                self.booksFound = tableItems

                self.tableView.reloadData()

            } catch {
                print("Error with JSON: ")
            }
        }
        queryTask.resume()
    }
}

extension TextbookSearchViewController: UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return booksFound.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)

        if let volumeInfo = self.booksFound[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
            cell.textLabel?.text = volumeInfo["title"] as? String
            cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
        }
        return cell
    }
}

extension TextbookSearchViewController: UISearchBarDelegate {
    func searchBarButtonClicked(searchBar: UISearchBar) {
        let bookTitle = searchBar.text?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        self.queryBooks(bookTitle: bookTitle!)
        searchBar.resignFirstResponder()
    }
}

最佳答案

可能您忘记设置UISearchBar delegate

@IBOutlet weak var searchBar: UISearchBar! {
  didSet {
    searchBar.delegate = self
  }
}

另外,您需要在下面代替func searchBarButtonClicked(searchBar: UISearchBar)
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    // your code
}

响应的关键是items而不是Items
使用json["items"]代替json [“Items”]

完整的代码:
import UIKit

class TextbookSearchViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var searchBar: UISearchBar! {
        didSet {
            searchBar.delegate = self
        }
    }
    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.delegate = self
            tableView.dataSource = self
        }
    }

    var booksFound = [[String: AnyObject]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

}

extension TextbookSearchViewController: UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return booksFound.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)

        if let volumeInfo = self.booksFound[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
            cell.textLabel?.text = volumeInfo["title"] as? String
            cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
        }
        return cell
    }
}

extension TextbookSearchViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let bookTitle = searchBar.text?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        queryBooks(bookTitle: bookTitle!)
        searchBar.resignFirstResponder()
    }

    func queryBooks(bookTitle: String) {
        let stringURL = "https://www.googleapis.com/books/v1/volumes?q=\(bookTitle)"
        guard let url = URL(string: stringURL) else {
            print("Problem with URL")
            return
        }
        let urlRequest = URLRequest(url: url as URL)
        let urlSession = URLSession.shared
        let queryTask = urlSession.dataTask(with: urlRequest) { [weak self] (data, response, error) in
            guard let jsonData = data else {
                print("No Information could be Found:")
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject]

                guard let tableItems = json["items"] as? [[String: AnyObject]] else {
                    self?.booksFound = [[String: AnyObject]]()
                    return
                }

                print(tableItems)
                self?.booksFound = tableItems

                DispatchQueue.main.async {
                    self?.tableView.reloadData()
                }
            } catch {
                print("Error with JSON: ")
            }
        }
        queryTask.resume()
    }
}

关于ios - 当我在搜索栏中键入以检索Google图书信息时,无法重新加载我的表格 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53268618/

10-12 04:08