ios - UISearch is not Working in JSON api UITable View -


all

i trying develop app. need search video list using uisearch view.

here code. can see search bar it's not working.

import uikit import googlemobileads

class viewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource, gadinterstitialdelegate, uialertviewdelegate, uisearchbardelegate {

@iboutlet weak var tblvideos: uitableview!  @iboutlet weak var banner3: gadbannerview!   var interstitial: gadinterstitial!   @iboutlet weak var viewwait: uiview!    var channelsdataarray: array<dictionary<string, any>> = []  var apikey = ""  var selectedvideoindex: int!   override func viewdidload() {     super.viewdidload()     // additional setup after loading view, typically nib.      if connectedtonetwork() == true {          tblvideos.delegate = self         tblvideos.datasource = self          print("google mobile ads sdk version: " + gadrequest.sdkversion())         banner3.adunitid = ""         banner3.rootviewcontroller = self         banner3.load(gadrequest())          getchanneldetails(false)         loadinterstitial()         searchbar()      }      else {         let controller = uialertcontroller(title: "no internet detected", message: "this app requires internet connection", preferredstyle: .alert)         let ok = uialertaction(title: "ok", style: .default, handler: nil)         let cancel = uialertaction(title: "cancel", style: .cancel, handler: nil)          controller.addaction(ok)         controller.addaction(cancel)          present(controller, animated: true, completion: nil)     } }  override func didreceivememorywarning() {     super.didreceivememorywarning()     // dispose of resources can recreated. }  func searchbar() {     let searchbar = uisearchbar(frame: cgrect(x: 0, y: 0, width: self.view.frame.width, height: 50))     searchbar.delegate = self     searchbar.showsscopebar = true     searchbar.tintcolor = uicolor.lightgray     self.tblvideos.tableheaderview = searchbar  }   func searchbar(_ searchbar: uisearchbar, textdidchange searchtext: string) {      if searchtext == "" {         //do         getchanneldetails(false)     }     else {              channelsdataarray = channelsdataarray.filter({($0["title"] as! string).contains(searchtext)})      }  }   override func prepare(for segue: uistoryboardsegue, sender: any?) {     if let playerviewcontroller = segue.destination as? playerviewcontroller {         playerviewcontroller.videoid = channelsdataarray[selectedvideoindex]["videoid"] as! string     } }     // mark: uitableview method implementation  func numberofsections(in tableview: uitableview) -> int {     return 1 }   func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int {      return channelsdataarray.count   }   func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell {     var cell: uitableviewcell!       cell = tableview.dequeuereusablecell(withidentifier: "idcellchannel", for: indexpath)      let channeltitlelabel = cell.viewwithtag(10) as! uilabel      let thumbnailimageview = cell.viewwithtag(12) as! uiimageview      let channeldetails = channelsdataarray[indexpath.row]     channeltitlelabel.text = channeldetails["title"] as? string      thumbnailimageview.image = uiimage(data: try! data(contentsof: url(string: (channeldetails["url"] as? string)!)!))       return cell }   func tableview(_ tableview: uitableview, heightforrowat indexpath: indexpath) -> cgfloat {     return 350.0 }   func tableview(_ tableview: uitableview, didselectrowat indexpath: indexpath) {      selectedvideoindex = indexpath.row     performsegue(withidentifier: "idsegueplayer", sender: self)     if (interstitial!.isready) {         interstitial!.present(fromrootviewcontroller: self)     }     loadinterstitial()  }        // mark: uitextfielddelegate method implementation    // mark: custom method implementation  func performgetrequest(_ targeturl: url!, completion: @escaping (_ data: data?, _ httpstatuscode: int, _ error: error?) -> void) {     var request = urlrequest(url: targeturl)     request.httpmethod = "get"      let sessionconfiguration = urlsessionconfiguration.default      let session = urlsession(configuration: sessionconfiguration)      let task = session.datatask(with: request, completionhandler: { (data: data?, response: urlresponse?, error: error?) -> void in         dispatchqueue.main.async(execute: { () -> void in             completion(data, (response as! httpurlresponse).statuscode, error)         })     } )      task.resume() }   func getchanneldetails(_ usechannelidparam: bool) {     var urlstring: string!     if !usechannelidparam {         urlstring = "https://www.googleapis.com/youtube/v3/search?part=id%2csnippet&type=video&q=mufti+amir+hamza&maxresults=50&key=apikey"     }      let targeturl = url(string: urlstring)      performgetrequest(targeturl, completion: { (data, httpstatuscode, error) -> void in         if httpstatuscode == 200 && error == nil {              {                  if let resultsdict = try jsonserialization.jsonobject(with: data!, options: []) as? [string:any] {                     if let items = resultsdict["items"] as? [[string:any]] {                         item in items {                             var desiredvalues = [string:any]()                              //get videoid                             if let id = item["id"] as? [string:any], let videoid = id["videoid"] as? string{                                 desiredvalues["videoid"] = videoid                             }                              //get title , thumbnail snippet                             if let snippet = item["snippet"] as? [string:any] {                                 if let title = snippet["title"] {                                     desiredvalues["title"] = title                                 }                                 if let thumbanail = snippet["thumbnails"] as? [string:any], let highvalues = thumbanail["high"] as? [string:any], let url = highvalues["url"] as? string {                                     desiredvalues["url"] = url                                 }                             }                             self.channelsdataarray.append(desiredvalues)                         }                         dispatchqueue.main.async {                             self.tblvideos.reloaddata()                         }                     }                  }             }             catch (let error){                 print("error while parsing data: \(error.localizeddescription)")             }         }          self.viewwait.ishidden = true      }) }     //inter  fileprivate func loadinterstitial() {     interstitial = gadinterstitial(adunitid: "")     interstitial!.delegate = self      // request test ads on devices specify. test device id printed console when     // ad request made.     interstitial!.load(gadrequest()) }   // mark: gadinterstitialdelegate implementation  func interstitialdidfailtoreceiveadwitherror (     _ interstitial: gadinterstitial,     error: gadrequesterror) {     print("interstitialdidfailtoreceiveadwitherror: %@" + error.localizeddescription) }  func interstitialdiddismissscreen (_ interstitial: gadinterstitial) {     print("interstitialdiddismissscreen")  } 

}

i need filter list titile. can please me solved it?

you need declare var filteredarray keep original array elements

something this

var filteredchannelsdataarray : array<dictionary<string, any>> = [] 

you need add line after self.channelsdataarray.append(desiredvalues) in getchanneldetails method

self.filteredchannelsdataarray = channelsdataarray 

try this

replace this

    func searchbar(_ searchbar: uisearchbar, textdidchange searchtext: string) {      if searchtext == "" {         //do         getchanneldetails(false)     }     else {           channelsdataarray = channelsdataarray.filter({ (alldata) -> bool in          return true      })      }  } 

by this

    func searchbar(_ searchbar: uisearchbar, textdidchange searchtext: string) {      if searchtext == "" {         //do         getchanneldetails(false)         self.filteredchannelsdataarray = channelsdataarray         self.tableview.reloaddata()     }     else {              self.filteredchannelsdataarray = channelsdataarray.filter({($0["title"] as! string).contains(searchtext)})            self.tableview.reloaddata()     }  } 

you need make few changes in uitableviewdatasource methods

func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int {     return self.filteredchannelsdataarray.count }  func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell {     var cell: uitableviewcell!       cell = tableview.dequeuereusablecell(withidentifier: "idcellchannel", for: indexpath)      let channeltitlelabel = cell.viewwithtag(10) as! uilabel      let thumbnailimageview = cell.viewwithtag(12) as! uiimageview      let channeldetails = self.filteredchannelsdataarray[indexpath.row]     channeltitlelabel.text = channeldetails["title"] as? string      thumbnailimageview.image = uiimage(data: try! data(contentsof: url(string: (channeldetails["url"] as? string)!)!))       return cell } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -