1

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()
       
    }
}
Jordan
  • 127
  • 1
  • 1
  • 9
  • Could you print `response` and see the URL of the response? Does it include the correct one? You know that the call are async, so there is no guarante when typing for instance "the", that you'll get the response in order for "t", "th", "the", but it could be "the", "t", then "th"? – Larme Apr 04 '22 at 15:53
  • @Larme It looks like it's giving the correct response. When I add "&maxResults=1" to the end of the search query URL, then I get the correct book. But as soon as the max results change to any other number then everything gets reordered. – Jordan Apr 04 '22 at 16:08

0 Answers0