ios - Trouble Populating UISearchBarController Results TableView -


i'm new swift, gentle.

i'm using xcode 7 beta, currently.

i have tableviewcontroller nested in navigationcontroller. within tableview i've implemented uisearchbar , uisearchdisplaycontroller similar steps here. pretty working expected, except when type search criteria, results table view uisearchdisplaycontroller not getting populated. when hit cancel on search, results have been populated in initial table view.

the tutorial linked pre-populating list of items , search bar filtering these items. approach different because i'm populating search external api.

my question two-fold:

a) how populate results tableview?

b) 2 tableviews seem redundant , don't feel first necessary (might wrong). what's proper way achieve functionality? ideally, able put uisearchbar in navigation item lives in uinavigationbar, have had trouble finding resources doing that.

import uikit import alamofire import swiftyjson import foundation  class dstableviewcontroller: uitableviewcontroller, uisearchbardelegate, uisearchdisplaydelegate {    var songs: [song] = []   var timer: nstimer = nstimer()    func getsongs(timer: nstimer!) {      let searchterm = timer.userinfo as! string      self.title = "results \(searchterm)"      // logic switch service; need move interface     // or move code inside rest api, , interface      // url encode search term     let searchtermencoded = searchterm.stringbyaddingpercentencodingwithallowedcharacters(.urlhostallowedcharacterset())      // create url web request     let uri: string = "https://api.spotify.com/v1/search?q=\(searchtermencoded!)&type=artist,album,track"      // call spotify api     alamofire         .request(.get, uri)         .response { request, response, data, error in              let json = json(data: data!)              print(json["tracks"]["items"].count);             print(json["tracks"]["items"])              var = 0; < json["tracks"]["items"].count; i++ {                  let data = json["tracks"]["items"][i]                  // return object list                 let song = song()                  song.title = data["name"].string!                 song.album = data["album"]["name"].string!                 song.artist = data["artists"][0]["name"].string!                  self.songs += [song]              }              dispatch_async(dispatch_get_main_queue()) {                 self.tableview!.reloaddata()             }       }    }    override func viewdidload() {     super.viewdidload()      // uncomment following line preserve selection between presentations     // self.clearsselectiononviewwillappear = false      // uncomment following line display edit button in navigation bar view controller.     // self.navigationitem.rightbarbuttonitem = self.editbuttonitem()   }    func searchdisplaycontroller(controller: uisearchdisplaycontroller, shouldreloadtableforsearchstring searchstring: string?) -> bool {      timer.invalidate()      timer = nstimer.scheduledtimerwithtimeinterval(0.5, target: self, selector: selector("getsongs:"), userinfo: searchstring, repeats: false)      return true    }    override func didreceivememorywarning() {     super.didreceivememorywarning()     // dispose of resources can recreated.   }    // mark: - table view data source    override func numberofsectionsintableview(tableview: uitableview) -> int {     // #warning incomplete implementation, return number of sections     return 1   }    override func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {     // #warning incomplete implementation, return number of rows     return songs.count   }     override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {     let cell = self.tableview.dequeuereusablecellwithidentifier("songcell", forindexpath: indexpath)      let song = songs[indexpath.row]      cell.textlabel?.text = song.title     cell.detailtextlabel?.text = song.artist + " - " + song.album     cell.imageview?.image = song.albumimage      return cell   } } 

when call

func searchdisplaycontroller(controller: uisearchdisplaycontroller, shouldreloadtableforsearchstring searchstring: string?) -> bool {      self.getsongs(searchstring)      return true    } 

i'm able populate view correctly, i'd have delay i'm not making api call every time text changes.

hopefully explained correctly. please feel free edit question if wasn't clear or missed something.

so ended getting functionality wanted , ended answering question of proper approach was. turns out trying fit square peg in round hole.

what ended doing removing uisearchdisplaycontroller altogether , instead creating uisearchbar , assigning self.navigationitem.titleview. removed of built-in functionality of search controller, gave me more concise way of doing needed do, without worrying silly workarounds. code looks like

class tableviewcontroller: uisearchbardelegate {      override func viewdidload() {         super.viewdidload()          let searchbar: uisearchbar = uisearchbar()          searchbar.placeholder = "search"         searchbar.delegate = self          self.navigationitem.titleview = searchbar          self.definespresentationcontext = true     }       func searchbar(searchbar: uisearchbar, textdidchange searchtext: string) {         timer.invalidate()          timer = nstimer.scheduledtimerwithtimeinterval(0.5, target: self, selector: "getresults:", userinfo: searchtext, repeats: false)     }      func searchbarsearchbuttonclicked(searchbar: uisearchbar) {         searchbar.resignfirstresponder()     }  } 

this approach got me functionality looking (being able delay call api until user done typing) , able remove code extraneous. helps in future.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -