• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 当我在搜索栏中键入以检索 Google 图书信息时,我的表格 View 未重新加载

[复制链接]
菜鸟教程小白 发表于 2022-12-11 20:48:22 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

这是我用来查找特定书籍的 Controller 。当我在搜索栏中键入时,在我键入时或在我完成键入后不会向我显示任何书籍信息。我想了解原因并找到解决此问题的解决方案。

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("roblem 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()
    }
}



Best Answer-推荐答案


可能你忘记设置 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("roblem 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap