I have set up a tableview that retrieves data from a firebase realtime database, and stores this data in an array ('posts') in this is the format:
(name: nil, contactEmail: Optional("35345345235"), contactPhoneNum: Optional("contact#gmail.com"), age: Optional("25"), gender: nil, lastSeen: nil, profileDescription: nil)
I want to implement a searchbar to filter the name value of the posts and return the posts which contain the searched name in the tableview, and am not sure how to do this.
Here is my code:
import UIKit
import Firebase
import FirebaseDatabase
import SwiftKeychainWrapper
import FirebaseAuth
class FeedVC: UITableViewController, UISearchBarDelegate{
#IBOutlet weak var searchBar: UISearchBar!
var currentUserImageUrl: String!
var posts = [postStruct]()
var selectedPost: Post!
var filteredPosts = [postStruct]()
override func viewDidLoad() {
super.viewDidLoad()
getUsersData()
getPosts()
searchBar.delegate = self
// Do any additional setup after loading the view.
// tableView.register(PostCell.self, forCellReuseIdentifier: "PostCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getUsersData(){
guard let userID = Auth.auth().currentUser?.uid else { return }
Database.database().reference().child("users").child(userID).observeSingleEvent(of: .value) { (snapshot) in
if let postDict = snapshot.value as? [String : AnyObject] {
self.tableView.reloadData()
}
}
}
struct postStruct {
let name : String!
let contactEmail : String!
let contactPhoneNum : String!
let age : String!
let gender : String!
let lastSeen : String!
let profileDescription : String!
}
func getPosts() {
let databaseRef = Database.database().reference()
databaseRef.child("firstName").queryOrderedByKey().observe( .childAdded, with: {
snapshot in
let name = (snapshot.value as? NSDictionary)!["name"] as? String
let contactEmail = (snapshot.value as? NSDictionary
)!["contactEmail"] as? String
let contactPhoneNum = (snapshot.value as? NSDictionary
)!["contactPhoneNum"] as? String
let age = (snapshot.value as? NSDictionary
)!["age"] as? String
let gender = (snapshot.value as? NSDictionary
)!["gender"] as? String
let lastSeen = (snapshot.value as? NSDictionary
)!["lastSeen"] as? String
let profileDescription = (snapshot.value as? NSDictionary
)!["profileDescription"] as? String
self.posts.append(postStruct(name: name,contactEmail:contactEmail, contactPhoneNum:contactPhoneNum, age:age, gender:gender, lastSeen:lastSeen, profileDescription:profileDescription))
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("posts count = ", filteredPosts.count)
return filteredPosts.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// tableView.dequeueReusableCell(withIdentifier: "PostCell")!.frame.size.height
return 230
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell else { return UITableViewCell() }
cell.nameLabel?.text = filteredPosts[indexPath.row].name
cell.contactEmailLabel?.text = filteredPosts[indexPath.row].contactEmail
cell.contactPhoneNumLabel?.text = filteredPosts[indexPath.row].contactPhoneNum
cell.ageLabel?.text = filteredPosts[indexPath.row].age
cell.genderLabel?.text = filteredPosts[indexPath.row].gender
cell.lastSeenLabel?.text = filteredPosts[indexPath.row].lastSeen
cell.profileDescriptionLabel?.text = filteredPosts[indexPath.row].profileDescription
print(filteredPosts)
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredPosts = posts.filter { $0.name?.lowercased().contains(searchText.lowercased()) == true }
}
}
Looping over the posts will provide element of type Post not String. Here's the fix:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredPosts = []
for post in posts {
if post.name?.lowercased().contains(searchText.lowercased()) == true {
filteredPosts.append(post)
}
}
}
Or simply use a higher-order method like filter inspired from #Jay's comment.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredPosts = posts.filter { $0.name?.lowercased().contains(searchText.lowercased()) == true }
}
Related
I really need help with this because i'm not sure how to troubleshoot this issue. I'm trying to make my view controller as though when i'm searching for a particular booth name and the value increments from Firebase, only the Booth names that are in my search bar updates instead of reloading the whole booth and updating it(Thus making my search bar useless).
Maybe my screenshots will give you a better idea of the issue. IF you still do not get it, feel free to comment and ask me because i know this is quite complicated. Thanks!
import UIKit
import FirebaseDatabase
var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData2 = [String]()
var currentpostDataArray = [String]()
var filteredDataArray = [tableData]()
var tableDataArray = [tableData]()
class TableViewController: UITableViewController, UISearchBarDelegate {
#IBOutlet var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
setUpSearchBar()
ref = Database.database().reference() //set the firebase reference
// Retrieve the post and listen for changes
databaseHandle = ref?.child("Posts").observe(.value, with: { (snapshot) in
currentpostDataArray.removeAll()
postData2.removeAll()
tableDataArray.removeAll()
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = String(describing: snap.value!)
let rating = (value as NSString).integerValue
tableDataArray.append(tableData(boothName: key, boothRating: rating))
}
let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
self.tableView.reloadData()
})
}
private func setUpSearchBar() {
searchBar.delegate = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return currentpostDataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = currentpostDataArray[indexPath.row]
cell.detailTextLabel?.text = postData2[indexPath.row] + " ♥"
cell.detailTextLabel?.textColor = UIColor.red;
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
currentpostDataArray.removeAll()
postData2.removeAll()
if(searchText.isEmpty)
{
let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
else {
let allBooth = tableDataArray.filter{$0.boothName.lowercased().contains(searchText.lowercased())}
let sortedTableData = allBooth.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
tableView.reloadData()
}
//Enable "Cancel" button on Search Bar
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsCancelButton = true
return true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.searchBar.endEditing(true)
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
currentpostDataArray.removeAll()
postData2.removeAll()
let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
self.tableView.reloadData()
self.searchBar.endEditing(true)
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
}
}
class tableData {
var boothName: String
var boothRating: Int
init(boothName: String, boothRating: Int) {
self.boothName = boothName
self.boothRating = boothRating
}
}
SCREENSHOTS: https://ibb.co/cN1XzG https://ibb.co/it3eeG https://ibb.co/bDMAmw
I tried to retrieving data from Firebase database to tableview in Xcode
but I just got one element even if I have a lot of element in the database.
I followed a tutorial, I put return sonsList.count to numberOfRowsInSection as suppose but nothing happen.
Here is my code:
import UIKit
import Firebase
import FirebaseDatabase
class sons {
let name : String!
//let place : String!
init(title_String : String!){
self.name = title_String
// self.place = place_String
}
}
class sonsTableViewController: UITableViewController {
var ref:DatabaseReference!
//var sons = [String]()
var newSon: String = ""
let cellId = "cellId"
var refHandel : uint!
var sonsList = [sons]()
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
ref.child("name").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: { snapshot in
let value = snapshot.value as? NSDictionary
let name = value!["name"] as! String
self.sonsList.append(sons(title_String : name))
self.tableView.reloadData()
})
//fetchName()
}
func fetchName() {
}
#IBAction func cancel(segue:UIStoryboardSegue) {
}
#IBAction func done(segue:UIStoryboardSegue) {
var sonDetailVC = segue.source as! addSonViewController
newSon = sonDetailVC.name
// sons.append(newSon)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sonsList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let label = cell?.viewWithTag(1) as! UILabel
label.text = sonsList[indexPath.row].name
return cell!
}
}
You have issues in your Database query.
You append only one value in sonsList.
ref = Database.database().reference()
ref.child("name").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: { snapshot in
//Parse snapshot value correctly it is array or not.
if let dicValue = snapshot.value as? [String : Any] {
for (key,value) in dicValue {
let name = value["name"] as? String
self.sonsList.append(sons(title_String : name))
}
self.tableView.reloadData()
}
})
Please refer this link for Get data in firebase Database.
https://firebase.google.com/docs/database/ios/read-and-write
Hey guys i've searched for hours and still cant find a proper way to search though my data base. I have an array of contact objects that have a username and name property and I have a "add user" view controller where the GOAL is to loop through all the users in my data base , and when searching , it widdles down the users in a UITABLEVIEW this is what I have so far.
Cliff notes of code below:
I get all my user objects from my database and store them in an array of type [contact] called "results" (custom object) then i attempt to filter the results and store those into a new array called "filteredData" Contact has type "userName" (String) which I would like to filter results by
import UIKit
import Firebase
class SearchForUsersViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
var results = [Contact]()
var filteredData = [Contact]()
var isSearching = false;
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self;
searchBar.returnKeyType = UIReturnKeyType.done
getUserList()
}
#IBAction func dismiss(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func getUserList(){
//populates results
staticValuesForData.instance.dataBaseUserref.observe( .value) { (snapshot) in
if let userList = snapshot.children.allObjects as? [DataSnapshot]{
for user in userList{
let name = (user.childSnapshot(forPath: staticValuesForData.instance.fName).value as! String) + " "
+ (user.childSnapshot(forPath: staticValuesForData.instance.lname).value as! String)
let contact = Contact(name: name , uid: user.key,
pic: user.childSnapshot(forPath: staticValuesForData.instance.profileUrl).value as! String,
userName: user.childSnapshot(forPath: staticValuesForData.instance.userName).value as! String )
print(contact.name)
print("user" , user)
self.results.append(contact)
}
}
}
}
}
table view extension :
extension SearchForUsersViewController : UITableViewDataSource ,
UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching{
return results.count
}
return 0;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell" , for: indexPath) as! AddedMeTableViewCell;
cell.profilePicture.loadImageUsingCacheWithUrlString(urlString: filteredData[indexPath.item].picUrl)
if isSearching{
cell.userName.text = filteredData[indexPath.item].userName!
}
else
{
cell.userName.text = results[indexPath.item].userName!
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
Search extension (where the issue is )
extension SearchForUsersViewController : UISearchBarDelegate{
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == "" || searchBar.text == nil{
view.endEditing(true)
isSearching = false;
tableView.reloadData()
}
else{
isSearching = true
ifSearchContains(word: searchBar.text!)
tableView.reloadData()
print(filteredData)
print(results)
print(searchBar.text)
}
}
func ifSearchContains(word : String)
{
for result in results{
if result.name.contains(word){
filteredData.append(result)
}else{
}
}
}
}
I have the search function above but it is not filtering , nor is the idea of it very efficient. this application is going to have thousands of users, can you please help me filter a search in an efficient way? Thank you so much
Here is the contact custom object just in case
import Foundation
class Contact : NSObject , Comparable{
let name : String!
let uid : String!
let picUrl : String!
let userName : String!
init(name : String , uid : String , pic : String , userName : String) {
self.name = name
self.uid = uid
self.picUrl = pic
self.userName = userName
}
static func ==(lhs: Contact, rhs: Contact) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Contact, rhs: Contact) -> Bool {
return lhs.name < rhs.name
}
}
I am trying to download data and put it in struct objects and trying to load data in table view .I am downloading it in to array and append it to struct object.when I am taking return array.count in no of rows in section its working when I use return objectArray[section].funcName.count its not working values are getting late to download also
import UIKit
import Alamofire
class GalleryVC: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var galleryTable: UITableView!
var imageUrlArray:[String] = [String]()
var imageCount:[String] = [String]()
var funName1:[String] = [String]()
var gaimage1:String = ""
var gacount1:String = ""
var funname1:String = ""
struct Objects {
var imageName : [String]!
var imageCount : [String]!
var funcName:[String]!
}
var objectArray = [Objects]()
var objectArrayFilter = [Objects]()
var inSearchMode = false
override func viewDidLoad() {
super.viewDidLoad()
downloadGalleryList()
galleryTable.delegate = self
galleryTable.dataSource = self
searchBar.delegate = self
self.hideKeyboardWhenTappedAround()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
print(objectArray[section].funcName.count)
return objectArray[section].funcName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:"gallerycell", for: indexPath) as? GalleryListCell{
if inSearchMode{
cell.galleryImage.sd_setImage(with: URL(string: objectArrayFilter[indexPath.section].imageName[indexPath.row]), placeholderImage: UIImage(named: "1862205"))
cell.galleryphotono.text = objectArrayFilter[indexPath.section].imageCount[indexPath.row]+" photos"
cell.galleryFunction.text = objectArrayFilter[indexPath.section].funcName[indexPath.row]
return cell
}
cell.galleryImage.sd_setImage(with: URL(string: objectArray[indexPath.section].imageName[indexPath.row]), placeholderImage: UIImage(named: "1862205"))
cell.galleryphotono.text = objectArray[indexPath.section].imageCount[indexPath.row]+" photos"
cell.galleryFunction.text = objectArray[indexPath.section].funcName[indexPath.row]
return cell
}
else{
return UITableViewCell()
}
}
func downloadGalleryList(){
let bmiChapterUrl = URL(string:Gallery_List)!
Alamofire.request(bmiChapterUrl).responseJSON{ response in
let result = response.result
print(response)
print(result)
if let dict = result.value as? Dictionary<String,AnyObject>{
if let bmi = dict["result"] as? [Dictionary<String,AnyObject>]
{
for obj in bmi {
if let gaimage = obj["image"] as? String
{
print(gaimage)
self.gaimage1 = gaimage
self.imageUrlArray.append(gaimage)
}
if let gacount = obj["count"] as? String
{
self.gacount1 = gacount
print(gacount)
self.imageCount.append(gacount)
}
if let funname = obj["event"] as? String
{
print(funname)
self.funname1 = funname
self.funName1.append(funname)
}
}
}
}
print(self.imageUrlArray,self.imageCount,self.funName1
)
self.objectArray.append(Objects(imageName: self.imageUrlArray, imageCount:self.imageCount,funcName: self.funName1))
print(self.objectArray)
self.galleryTable.reloadData()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
galleryTable.reloadData()
} else {
inSearchMode = true
objectArrayFilter = objectArray.filter { $0.imageName.contains(where: { $0.contains(searchBar.text!) }) }
print(objectArrayFilter)
galleryTable.reloadData()
}
}
}
I am loading my plist into a TableView and it is going everything ok, but now I am trying to include a SearchBar on the Page1. Below you see the directory.plist and my Main.storyboard
To load the plist correctly I put the following code on my didFinishLaunchingWithOptions:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let url = Bundle.main.url(forResource: "directory", withExtension: "plist"), let array = NSArray(contentsOf: url) as? [[String:Any]] {
Shared.instance.employees = array.map{Employee(dictionary: $0)}
}
return true
}
I also have a Structure helping me to load all my stuff:
struct EmployeeDetails {
let functionary: String
let imageFace: String
let phone: String
init(dictionary: [String: Any]) {
self.functionary = (dictionary["Functionary"] as? String) ?? ""
self.imageFace = (dictionary["ImageFace"] as? String) ?? ""
self.phone = (dictionary["Phone"] as? String) ?? ""
}
}
struct Employee {
let position: String
let name: String
let details: [EmployeeDetails] // [String:Any]
init(dictionary: [String: Any]) {
self.position = (dictionary["Position"] as? String) ?? ""
self.name = (dictionary["Name"] as? String) ?? ""
let t = (dictionary["Details"] as? [Any]) ?? []
self.details = t.map({EmployeeDetails(dictionary: $0 as! [String : Any])})
}
}
struct Shared {
static var instance = Shared()
var employees: [Employee] = []
}
Until here, everything is running well! Now I became having trouble when I tried to insert a SearchView, take a look what I did until now:
class Page1: UITableViewController, UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
let employeesSearching: [String] = [String]() //now using: var employeesSearching = [Employee]()
var isSearching : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.isSearching == true {
return self.employeesSearching.count
} else {
return Shared.instance.employees.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
let employee = Shared.instance.employees[indexPath.row]
if self.isSearching == true {
cell.nameLabel.text = self.employeesSearching[indexPath.row].name
cell.positionLabel.text = self.employeesSearching[indexPath.row].position
} else {
cell.nameLabel.text = employee.name
cell.positionLabel.text = employee.position
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if self.searchBar.text!.isEmpty {
self.isSearching = false
self.tableView.reloadData()
} else {
self.isSearching = true
self.employeesSearching.removeAll(keepingCapacity: false)
for i in 0..<self.Shared.instance.itens.count {
let listItem : String = self.Shared.instance.itens[i]
if listItem.lowercased().range(of: self.searchBar.text!.lowercased()) != nil {
self.employeesSearching.append(listItem)
}
}
self.tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? Page2,
let indexPath = tableView.indexPathForSelectedRow {
destination.newPage = Shared.instance.employees[indexPath.row]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
These are the exactly mistakes:
EDIT 1
After tips, now the only trouble is:
EDIT 2
Now I am having this:
The errors are because employeesSearching is a constant array of String.
You probably want a variable array of Employee.
Change:
let employeesSearching: [String] = [String]()
to:
var employeesSearching = [Employee]()