UISearchBar和Firebase数据库

时间:2017-08-25 20:22:30

标签: swift uitableview sorting firebase uisearchbar

 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!

}

'另外,有没有人知道如何按字母顺序对tableview单元格(本例中的帖子)进行排序?'

3 个答案:

答案 0 :(得分:0)

您可以按字母顺序获取所有数据

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 }

样本结构

enter image description here

答案 1 :(得分:0)

根据searchBar对数据进行排序我使用了一个包含我所有快照的字典,并且我在该dict中比较了我的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
}

答案 2 :(得分:0)

我确信这对使用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!)")
            }
        }
    }
}