【问题标题】:UISearchBar and Firebase DatabaseUISearchBar 和 Firebase 数据库
【发布时间】:2017-08-25 20:22:30
【问题描述】:
 struct postStruct {
let title : String!
let author : String!
let bookRefCode : String!
let imageDownloadString : String!
let status : String!
let reserved : String!
let category : String!
let dueDate : String!
}

'上面是我为帖子设置结构的地方,下面是我如何从 firebase 数据库中引用和检索数据。

我的问题是,当您设置搜索器时,我不知道如何根据帖子的标题进行搜索。'

class DirectoryTableView: UITableViewController {

 var posts = [postStruct]()

override func viewDidLoad() {

    let databaseRef = Database.database().reference()

    databaseRef.child("Books").queryOrderedByKey().observe(.childAdded, with: {
        snapshot in

        var snapshotValue = snapshot.value as? NSDictionary
        let title = snapshotValue!["title"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let author = snapshotValue!["author"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let bookRefCode = snapshotValue!["bookRefCode"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let status = snapshotValue!["status"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let reserved = snapshotValue!["reserved"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let category = snapshotValue!["category"] as? String
        snapshotValue = snapshot.value as? NSDictionary

        let dueDate = snapshotValue!["dueDate"] as? String
        snapshotValue = snapshot.value as? NSDictionary


        self.posts.insert(postStruct(title: title, author: author, bookRefCode: bookRefCode, status: status, reserved: reserved, category: category, dueDate: dueDate) , at: 0)
        self.tableView.reloadData()


    })



override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count

}




override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let databaseRef = Database.database().reference()

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title

    let label2 = cell?.viewWithTag(2) as! UILabel
    label2.text = posts[indexPath.row].author

    let label3 = cell?.viewWithTag(3) as! UILabel
    label3.text = posts[indexPath.row].bookRefCode

    let label4 = cell?.viewWithTag(4) as! UILabel
    label4.text = posts[indexPath.row].status

    let label5 = cell?.viewWithTag(5) as! UILabel
    label5.text = posts[indexPath.row].category

    let image1 = cell?.viewWithTag(6) as! UILabel
    image1.text = posts[indexPath.row].imageDownloadString

    let label6 = cell?.viewWithTag(7) as! UILabel
    label6.text = posts[indexPath.row].reserved

    let label9 = cell?.viewWithTag(9) as! UILabel
    label9.text = posts[indexPath.row].dueDate

    return cell!

}

'另外,有谁知道如何按字母顺序对表格视图单元格(在这种情况下为帖子)进行排序?'

【问题讨论】:

    标签: swift uitableview sorting firebase uisearchbar


    【解决方案1】:

    你可以得到所有已经按字母顺序排列的数据

    databaseRef.child("Books").queryOrdered(byChild: "title").observe(.childAdded, with: { snapshot in
    
        var snapshotValue = snapshot.value as? NSDictionary
            let title = snapshotValue!["title"] as? String
            snapshotValue = snapshot.value as? NSDictionary
    
        ....
    
    }
    

    或在重新加载tableView之前对数组进行排序

    var sortedArray = swiftArray.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == ComparisonResult.orderedAscending }
    

    示例结构

    【讨论】:

    • 如果你使用第一种方法,我不会排序
    • 我编辑了我的答案。只需将.observe(.value, 更改为.observe(.childAdded。我在这里进行了测试,它对我有用。
    • @kileros 我们可以查询我的数据库是否有任何孩子的标题名称中有字母“a”,所以在 snapShot 中获取它?像“appcoda”里面有“a”还有更多这样的标题?
    • 我不相信使用 Firebase SDK 可以进行这种查询。一种方法是在查询您的项目后进行过滤。类似let snapshotValue = snapshot.value as! [String: AnyObject] let name = snapshotValue["name"] as! String if name.lowercased().characters.contains("a") { self.queriedArray.append(yourItem) }
    【解决方案2】:

    为了根据 searchBar 对数据进行排序,我使用了一个包含所有快照的字典,我比较了该字典中的 searchBar 文本,在对重新加载的 tableView 进行排序后,您可以查看这里的代码

    //method to get all user Details in a dict 
    
    func getEmail() {
    
        let databaseRef = Database.database().reference().child("users")
    
        databaseRef.observe(.value, with: { (snapshot) in
            if snapshot.exists(){
                self.postData = snapshot.value as! [String : AnyObject]
    
                let dictValues = [AnyObject](self.postData.values)
                self.sarchDict = dictValues
    
            }
        })
    }
    //search bar delegate
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    
    if self.mySearchBar.text!.isEmpty {
    
    // set searching false
    self.isSearching = false
    
    }else{
    
    // set searghing true
    self.isSearching = true
    
    self.names.removeAll()
    self.uidArray.removeAll()
    self.imageUrl.removeAll()
    
    for key in self.sarchDict {
    
    let mainKey = key
     //I am making query against email in snapshot dict
    
    
    let str = key["email"] as? String
    
        //taking value of email from my dict lowerCased to make query as case insensitive
    
    let lowercaseString = str?.lowercased()
                       //checking do my any email have entered letter or not 
     if(lowercaseString?.hasPrefix(self.mySearchBar.text!.lowercased()))!{
    
    //here I have a check so to remove value of current logged user 
    if ((key["uID"] as! String) != (Auth.auth().currentUser?.uid)!){
    
    //If value is found append it in some arrays 
     self.imageUrl.append( key["profilePic"] as! String )
     self.names.append( key["name"] as! String )
     self.uidArray.append( key["uID"] as! String )
    
    //you can check which values are being added from which key
     print(mainKey)
    
    }  
    }
    }
    //reload TableView here
    }     
    }
    
    //TableView
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        cell = self.myTableView.dequeueReusableCell(withIdentifier: "Cell")!
    
    
        if self.isSearching == true {
    
            let imageView = (cell.viewWithTag(1) as! UIImageView)
            imageView.setRounded()
            if imageUrl[indexPath.row] != "" {
                self.lazyImage.showWithSpinner(imageView:imageView, url:imageUrl[indexPath.row])
            }
            else{
                imageView.image = UIImage(named: "anonymous")
            }
    
    
            (cell.contentView.viewWithTag(2) as! UILabel).text = self.names[indexPath.row]
    
        }
        else {
    
    
        }
    
        return cell
    }
    

    【讨论】:

      【解决方案3】:

      我相信这对一些使用 FireStore 的人会有所帮助。在这里,我只是将我的引用设置为指向正确的集合。 “名称”是我希望搜索的字段,大于按时间顺序在我的字符串上检查的字段。他们键入的越多,搜索结果就越明确。

          static func searchForProgramStartingWith(string: String) {
      
          let programsRef = db.collection("programs")
      
          programsRef.whereField("name", isGreaterThan: string).limit(to: 10).getDocuments { (snapshot, error) in
      
              if error != nil {
                 print("there was an error")
              } else {
                  let shots = snapshot?.documents
      
                  for each in shots! {
                      let data = each.data()
                      let name = data["name"]
                      print("The name is \(name!)")
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 2019-05-10
        • 2021-07-20
        相关资源
        最近更新 更多