How to search in Firebase Database Swift





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















am trying to use UISearchbar with my firebase database but i don't know if my code is rghit or not becuase it's crash everytime i run it and this's my code



var hotelList = [hotelsModel]()
var hotelsArray : [NSDictionary] =
var filterHotels : [NSDictionary] =
var databaseRef = Database.database().reference()


databaseRef.child("Hotels").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in
self.hotelsArray.append(snapshot.value as! NSDictionary)

self.tableView.insertRows(at: [IndexPath(row: self.hotelsArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)




  1. List item



    }) { (error) in
    print(error.localizedDescription)
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //creating a cell using the custom class
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! hotelsTableViewCell



    let hotelSearch : NSDictionary?
    //the artist object
    var hotel: hotelsModel
    //getting the artist of selected position
    //hotel = hotelList[indexPath.row]
    if searchController.isActive && searchController.searchBar.text != "" {

    hotelSearch = filterHotels[indexPath.row] as! NSDictionary
    } else {
    //getting the artist of selected position
    hotel = hotelList[indexPath.row]
    }

    //getting the artist of selected position
    hotel = hotelList[indexPath.row]
    //adding values to labels
    cell.lblName.text = hotel.name
    cell.lblLocation.text = hotel.location
    cell.appSuggest.text = hotel.appSuggest
    cell.price.text = hotel.price
    cell.canceletion.text = hotel.cancelation
    cell.paymentNeeded.text = hotel.paymentNeeded

    if let imgUrl = hotel.img{
    let url = URL(string: imgUrl)
    cell.img.kf.setImage(with: url)
    cell.img.clipsToBounds = true
    cell.img.layer.cornerRadius = 10
    cell.img.layer.shadowColor = UIColor.black.cgColor
    cell.img.layer.shadowOpacity = 1.8
    cell.img.layer.shadowOffset = CGSize(width: 5, height: 0)
    }
    return cell


    }
    func updateSearchResults(for searchController: UISearchController) {
    //update the searchbar result
    //filterHotels(serachText:searchController.searchBar.text!)
    filterHotels.removeAll()
    filterHotels = hotelsArray.filter({ (text) -> Bool in
    let tmp: NSString = (text as? NSString ?? nil) ?? ""
    let range = tmp.range(of: searchController.searchBar.text!, options: NSString.CompareOptions.caseInsensitive)
    return range.location != NSNotFound
    })
    self.tableView.reloadData()
    }




it's crashed in this line



self.hotelsArray.append(snapshot.value as! NSDictionary)


How can I solve this?



Thank You










share|improve this question































    1















    am trying to use UISearchbar with my firebase database but i don't know if my code is rghit or not becuase it's crash everytime i run it and this's my code



    var hotelList = [hotelsModel]()
    var hotelsArray : [NSDictionary] =
    var filterHotels : [NSDictionary] =
    var databaseRef = Database.database().reference()


    databaseRef.child("Hotels").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in
    self.hotelsArray.append(snapshot.value as! NSDictionary)

    self.tableView.insertRows(at: [IndexPath(row: self.hotelsArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)




    1. List item



      }) { (error) in
      print(error.localizedDescription)
      }


      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      //creating a cell using the custom class
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! hotelsTableViewCell



      let hotelSearch : NSDictionary?
      //the artist object
      var hotel: hotelsModel
      //getting the artist of selected position
      //hotel = hotelList[indexPath.row]
      if searchController.isActive && searchController.searchBar.text != "" {

      hotelSearch = filterHotels[indexPath.row] as! NSDictionary
      } else {
      //getting the artist of selected position
      hotel = hotelList[indexPath.row]
      }

      //getting the artist of selected position
      hotel = hotelList[indexPath.row]
      //adding values to labels
      cell.lblName.text = hotel.name
      cell.lblLocation.text = hotel.location
      cell.appSuggest.text = hotel.appSuggest
      cell.price.text = hotel.price
      cell.canceletion.text = hotel.cancelation
      cell.paymentNeeded.text = hotel.paymentNeeded

      if let imgUrl = hotel.img{
      let url = URL(string: imgUrl)
      cell.img.kf.setImage(with: url)
      cell.img.clipsToBounds = true
      cell.img.layer.cornerRadius = 10
      cell.img.layer.shadowColor = UIColor.black.cgColor
      cell.img.layer.shadowOpacity = 1.8
      cell.img.layer.shadowOffset = CGSize(width: 5, height: 0)
      }
      return cell


      }
      func updateSearchResults(for searchController: UISearchController) {
      //update the searchbar result
      //filterHotels(serachText:searchController.searchBar.text!)
      filterHotels.removeAll()
      filterHotels = hotelsArray.filter({ (text) -> Bool in
      let tmp: NSString = (text as? NSString ?? nil) ?? ""
      let range = tmp.range(of: searchController.searchBar.text!, options: NSString.CompareOptions.caseInsensitive)
      return range.location != NSNotFound
      })
      self.tableView.reloadData()
      }




    it's crashed in this line



    self.hotelsArray.append(snapshot.value as! NSDictionary)


    How can I solve this?



    Thank You










    share|improve this question



























      1












      1








      1








      am trying to use UISearchbar with my firebase database but i don't know if my code is rghit or not becuase it's crash everytime i run it and this's my code



      var hotelList = [hotelsModel]()
      var hotelsArray : [NSDictionary] =
      var filterHotels : [NSDictionary] =
      var databaseRef = Database.database().reference()


      databaseRef.child("Hotels").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in
      self.hotelsArray.append(snapshot.value as! NSDictionary)

      self.tableView.insertRows(at: [IndexPath(row: self.hotelsArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)




      1. List item



        }) { (error) in
        print(error.localizedDescription)
        }


        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //creating a cell using the custom class
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! hotelsTableViewCell



        let hotelSearch : NSDictionary?
        //the artist object
        var hotel: hotelsModel
        //getting the artist of selected position
        //hotel = hotelList[indexPath.row]
        if searchController.isActive && searchController.searchBar.text != "" {

        hotelSearch = filterHotels[indexPath.row] as! NSDictionary
        } else {
        //getting the artist of selected position
        hotel = hotelList[indexPath.row]
        }

        //getting the artist of selected position
        hotel = hotelList[indexPath.row]
        //adding values to labels
        cell.lblName.text = hotel.name
        cell.lblLocation.text = hotel.location
        cell.appSuggest.text = hotel.appSuggest
        cell.price.text = hotel.price
        cell.canceletion.text = hotel.cancelation
        cell.paymentNeeded.text = hotel.paymentNeeded

        if let imgUrl = hotel.img{
        let url = URL(string: imgUrl)
        cell.img.kf.setImage(with: url)
        cell.img.clipsToBounds = true
        cell.img.layer.cornerRadius = 10
        cell.img.layer.shadowColor = UIColor.black.cgColor
        cell.img.layer.shadowOpacity = 1.8
        cell.img.layer.shadowOffset = CGSize(width: 5, height: 0)
        }
        return cell


        }
        func updateSearchResults(for searchController: UISearchController) {
        //update the searchbar result
        //filterHotels(serachText:searchController.searchBar.text!)
        filterHotels.removeAll()
        filterHotels = hotelsArray.filter({ (text) -> Bool in
        let tmp: NSString = (text as? NSString ?? nil) ?? ""
        let range = tmp.range(of: searchController.searchBar.text!, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
        })
        self.tableView.reloadData()
        }




      it's crashed in this line



      self.hotelsArray.append(snapshot.value as! NSDictionary)


      How can I solve this?



      Thank You










      share|improve this question
















      am trying to use UISearchbar with my firebase database but i don't know if my code is rghit or not becuase it's crash everytime i run it and this's my code



      var hotelList = [hotelsModel]()
      var hotelsArray : [NSDictionary] =
      var filterHotels : [NSDictionary] =
      var databaseRef = Database.database().reference()


      databaseRef.child("Hotels").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in
      self.hotelsArray.append(snapshot.value as! NSDictionary)

      self.tableView.insertRows(at: [IndexPath(row: self.hotelsArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)




      1. List item



        }) { (error) in
        print(error.localizedDescription)
        }


        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //creating a cell using the custom class
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! hotelsTableViewCell



        let hotelSearch : NSDictionary?
        //the artist object
        var hotel: hotelsModel
        //getting the artist of selected position
        //hotel = hotelList[indexPath.row]
        if searchController.isActive && searchController.searchBar.text != "" {

        hotelSearch = filterHotels[indexPath.row] as! NSDictionary
        } else {
        //getting the artist of selected position
        hotel = hotelList[indexPath.row]
        }

        //getting the artist of selected position
        hotel = hotelList[indexPath.row]
        //adding values to labels
        cell.lblName.text = hotel.name
        cell.lblLocation.text = hotel.location
        cell.appSuggest.text = hotel.appSuggest
        cell.price.text = hotel.price
        cell.canceletion.text = hotel.cancelation
        cell.paymentNeeded.text = hotel.paymentNeeded

        if let imgUrl = hotel.img{
        let url = URL(string: imgUrl)
        cell.img.kf.setImage(with: url)
        cell.img.clipsToBounds = true
        cell.img.layer.cornerRadius = 10
        cell.img.layer.shadowColor = UIColor.black.cgColor
        cell.img.layer.shadowOpacity = 1.8
        cell.img.layer.shadowOffset = CGSize(width: 5, height: 0)
        }
        return cell


        }
        func updateSearchResults(for searchController: UISearchController) {
        //update the searchbar result
        //filterHotels(serachText:searchController.searchBar.text!)
        filterHotels.removeAll()
        filterHotels = hotelsArray.filter({ (text) -> Bool in
        let tmp: NSString = (text as? NSString ?? nil) ?? ""
        let range = tmp.range(of: searchController.searchBar.text!, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
        })
        self.tableView.reloadData()
        }




      it's crashed in this line



      self.hotelsArray.append(snapshot.value as! NSDictionary)


      How can I solve this?



      Thank You







      swift firebase search firebase-realtime-database uisearchbar






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 14:05









      Frank van Puffelen

      245k30389418




      245k30389418










      asked Nov 16 '18 at 13:24









      Hamada RaoufHamada Raouf

      187




      187
























          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338785%2fhow-to-search-in-firebase-database-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338785%2fhow-to-search-in-firebase-database-swift%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine