@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
performSearch()
}
func iTunesURL(searchText: String, category: Int) -> URL {
let entityName: String
switch category {
case 1: entityName = "musicTrack"
case 2: entityName = "software"
case 3: entityName = "ebook"
default: entityName = ""
}
let escapedSearchText = searchText.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let urlString = String(format:"https://itunes.apple.com/search?term=%@&limit=200", escapedSearchText, entityName)
let url = URL(string: urlString)
inside extention
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
performSearch()
}
func performSearch() {
if !searchBar.text!.isEmpty {
searchBar.resignFirstResponder()
dataTask?.cancel()
isLoading = true
tableView.reloadData()
hasSearched = true
searchResults = []
let url = self.iTunesURL(searchText: searchBar.text!,
category: segmentedControl.selectedSegmentIndex)
let session = URLSession.shared
dataTask = session.dataTask(with: url, completionHandler: { data, response, error in
if let error = error as NSError?, error.code == -999 {
return
} else if let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 {
if let data = data, let jsonDictonary = self.parse(json: data) {
self.searchResults = self.parse(dictionary: jsonDictonary)
self.searchResults.sort(by: <)
DispatchQueue.main.async {
self.isLoading = false
self.tableView.reloadData()
}
return
}
} else {
print("Failure! \(response!)")
}
DispatchQueue.main.async {
self.hasSearched = false
self.isLoading = false
self.tableView.reloadData()
self.showNetWorkError()
}
})
dataTask?.resume()
}
}
my click my sigment control but its not work here is photo