2017-08-18 52 views
1

全部UISearch不工作在JSON api UITable查看

我想開發一個應用程序。現在我需要使用UISearch View來搜索視頻列表。

這是我的代碼。我可以看到搜索欄,但它不起作用。

進口的UIKit 進口GoogleMobileAds

類的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() 
    // Do any additional setup after loading the view, typically from a 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 an 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 any resources that can be 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 something 
     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 { 

      do { 

       if let resultsDict = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { 
        if let items = resultsDict["items"] as? [[String:Any]] { 
         for item in items { 
          var desiredValues = [String:Any]() 

          //get the videoId 
          if let id = item["id"] as? [String:Any], let videoId = id["videoId"] as? String{ 
           desiredValues["videoId"] = videoId 
          } 

          //get title and thumbnail from 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 you specify. Your test device ID is printed to the console when 
    // an ad request is made. 
    interstitial!.load(GADRequest()) 
} 


// MARK: GADInterstitialDelegate implementation 

func interstitialDidFailToReceiveAdWithError (
    _ interstitial: GADInterstitial, 
    error: GADRequestError) { 
    print("interstitialDidFailToReceiveAdWithError: %@" + error.localizedDescription) 
} 

func interstitialDidDismissScreen (_ interstitial: GADInterstitial) { 
    print("interstitialDidDismissScreen") 

} 

}

我只需要現在我過濾列表作爲Titile。可以請任何幫助我解決它?

+0

[這](https://stackoverflow.com/questions/36496791/filtering-array-of-dictionaries-in-swift)可能會幫助 – Hooda

+0

是您searcBar(_:didChange :)方法在搜索欄中輸入文字時被調用? – 3stud1ant3

+0

@ user1000是的,它被稱爲 –

回答

0

你需要聲明一個變種爲filteredArray保留原本的數組的元素都

像這樣

var filteredChannelsDataArray : Array<Dictionary<String, Any>> = [] 

您還需要self.channelsDataArray.append(desiredValues)後您getChannelDetails方法添加此行

self.filteredChannelsDataArray = channelsDataArray 

試一下

替換此

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 

    if searchText == "" { 
     //do something 
     getChannelDetails(false) 
    } 
    else { 

     channelsDataArray = channelsDataArray.filter({ (alldata) -> Bool in 

     return true 

    }) 

    } 

} 

通過這個

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 

    if searchText == "" { 
     //do something 
     getChannelDetails(false) 
     self.filteredChannelsDataArray = channelsDataArray 
     self.tableView.reloadData() 
    } 
    else { 

      self.filteredChannelsDataArray = channelsDataArray.filter({($0["title"] as! String).contains(searchText)}) 
      self.tableView.reloadData() 
    } 

} 

您還需要在您的UITableViewDataSource方法

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 
} 
0

一些改變,你可以用這個代碼嘗試:自.tblVideos。 reloadData()

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
    if searchText == "" { 
     //do something 
     getChannelDetails(false) 
    } 
    else { 

     channelsDataArray = channelsDataArray.filter({($0["title"] as! String).contains(searchText)}) 
     self.tblVideos.reloadData() 
    } 
}