Google Books Api gives wrong results in search

433 Views Asked by At

When I search for something like if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=regretting+you")

On my browser I get the correct results: enter image description here

But my debug console gives me these results enter image description here

It looks like its searching the search word minus the last letter, but I'm not sure why. When I search the same thing minus the last letter in the browser then I see the same results as the debug code, which is incorrect:

enter image description here

This is how I'm calling the API in my code:

func searchBooks() {
    if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=\(searchText)") {
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                do {
                    let response = try JSONDecoder().decode(ApiResponse.self, from: data)
                    self.bookInfo = response.items
                       for books in self.bookInfo {
                         print(books.volumeInfo.title, "title:")
                       
                      }
                } catch {
                    print(error)
                }
                
            }
            DispatchQueue.main.async {
                    print("URL:", url)
                    self.tableview.reloadData()
            }
            
        }.resume()
    }
}

and I call the searchText method from my searchBar:

extension ViewController: UISearchBarDelegate {

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    //The text has been changed
    modifySearchText()
    if tableview.visibleCells.isEmpty == false {
        print("tableview is not empty")
        scrollToTop()

    }
        
   
    
}

private func scrollToTop() {
    let topRow = IndexPath(row: 0, section: 0)
    self.tableview.scrollToRow(at: topRow, at: .top, animated: false)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    //search button has been clicked
    searchBar.resignFirstResponder()
    modifySearchText()
}

func modifySearchText() {
    print("modify running")
    let searchString = searchBar.text!
    self.searchText = searchString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil).lowercased()
        searchBooks()
       
    }
}
0

There are 0 best solutions below