searchBar in tableView enquiries (Swift) - ios

I don't really know how to explain thats why I'm putting this title. But i do hope you can understand. As of right now, my searchBar is able to return results BUT i have to enter the entire name (For example: I have to type "EcoBooth" in order for the searchBar to return EcoBooth results.).
How can i make it as though if i just enter "Eco", it will return EcoBooth based on just a few strings i type?
P.S: Do look at the 2 images attached for more info.
My TableView Controller codes
import UIKit
import FirebaseDatabase
var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var postData2 = [String]()
var currentpostDataArray = [String]()
var tableDataArray = [tableData]()
var searchArray = [tableData]()
var inSearchMode = false
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("Posts2").observe(.value, with: { (snapshot) in
// Code to execute when a child is added under "Posts"
postData.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
postData.append(key)
postData2.append(value)
tableDataArray.append(tableData(boothName: key, boothRating: rating))
currentpostDataArray = postData
}
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) {
searchArray.removeAll()
searchArray = tableDataArray
currentpostDataArray.removeAll()
postData2.removeAll()
if !searchText.isEmpty {
for data in searchArray {
let item = data.boothName
if (searchText.lowercased().range(of: item) != nil) || data.boothName.lowercased() == searchText.lowercased() || searchText.lowercased().contains(data.boothName.lowercased())
{
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
}
if searchText.isEmpty {
loadDara()
}
self.tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
switch selectedScope {
case 0:
currentpostDataArray.removeAll()
postData2.removeAll()
for data in tableDataArray {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
self.tableView.reloadData()
case 1:
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()
default:
break
}
tableView.reloadData()
}
func loadDara() {
for data in tableDataArray {
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
}
class tableData {
var boothName: String
var boothRating: Int
init(boothName: String, boothRating: Int) {
self.boothName = boothName
self.boothRating = boothRating
}
}

Replace
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray.removeAll()
searchArray = tableDataArray
currentpostDataArray.removeAll()
postData2.removeAll()
if !searchText.isEmpty {
for data in searchArray {
let item = data.boothName
if (searchText.lowercased().range(of: item) != nil) || data.boothName.lowercased() == searchText.lowercased() || searchText.lowercased().contains(data.boothName.lowercased())
{
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
}
if searchText.isEmpty {
loadDara()
}
self.tableView.reloadData()
}
With
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray.removeAll()
searchArray = tableDataArray
currentpostDataArray.removeAll()
postData2.removeAll()
if !searchText.isEmpty {
for data in searchArray {
let item = data.boothName
if (item.lowercased().range(of: searchText.lowercased()) != nil)
{
currentpostDataArray.append(data.boothName)
let value = String(describing: data.boothRating)
postData2.append(value)
}
}
}
if searchText.isEmpty {
loadDara()
}
self.tableView.reloadData()
}

Use NSPredicate to search from array like this:
let searchPredicate = NSPredicate(format: "boothName CONTAINS[C] %#", searchText)
resultArr = (filteredArray as NSArray).filtered(using: searchPredicate)
You can prefer this link for more info about NSPredicate and also a swift code example : http://nshipster.com/nspredicate/

Related

How do you search through firebase data in tableview with a SearchBar?

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

Search name or number in `UISearchbar`

In tableViewCell I have userNameLbl with name, userClgLbl with number. I want to search and show data in tableView either name search or number search.
If user search name - based on name I can show data in tableView.
If user search number - based on number I can show data in tableView.
But how to work with both name and number for single search bar. Actually here my data is dynamic from server and number is not phone number.
UISearchBarDelegate added to my class
let searchBar = UISearchBar()
var filteredData: [Any]!
#IBOutlet weak var listTblView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.userNameLbl.text = filteredData[indexPath.row] as? String
cell.userClgLbl.text = clg_uniq[indexPath.row] as? String
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let strArr:[String] = clg_uniq as! [String]
filteredData = searchText.isEmpty ? clg_uniq : strArr.filter({(dataString: String) -> Bool in
// If dataItem matches the searchText, return true to include it
return dataString.range(of: searchText, options: .caseInsensitive) != nil
})
DispatchQueue.main.async {
self.listTblView.reloadData()
}
if searchText == "" {
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
//Added these lines after json parsing
self.filteredData = self.clg_uniq
self.listTblView.reloadData()
My example JSON data is
{"log" = (
{
Name = "Name1";
"clg_uniq" = 5c640e7b86e35;
},
{
Name = "Name2";
"clg_uniq" = <null>;
},
{
Name = <null>;
"clg_uniq" = 5c647af5d5c4d;
},
{
Name = "Name4";
"clg_uniq" = 5c647a0427253;
},
{
Name = <null>;
"clg_uniq" = <null>;
},
{
Name = "Name6";
"clg_uniq" = $cuniq";
},
)
}
Add following variables -
var logArray = [Dictionary<String, Any>]() // For all result
var searchedLogArray = [Dictionary<String, Any>]() // For filtered result
var searchActive = false // whenever user search anything
Replace UISearchBarDelegate -
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchActive = searchText.count > 0 ? true : false
let namePredicate = NSPredicate(format: "Name CONTAINS[c] %#", searchText)
let clgUniqPredicate = NSPredicate(format: "clg_uniq CONTAINS[c] %#", searchText)
let compoundPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [namePredicate, clgUniqPredicate])
searchedLogArray = logArray.filter({
return compoundPredicate.evaluate(with: $0)
})
listTblView.reloadData()
}
Replace UITableViewDataSource -
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchActive ? searchedLogArray.count : logArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
let logDict = searchActive ? searchedLogArray[indexPath.row] : logArray[indexPath.row]
// Name
if let name = log["Name"] as? String{
cell.userNameLbl.text = name
}else{
cell.userNameLbl.text = ""
}
// clg_uniq
if let clgUniq = log["clg_uniq"] as? String {
cell.userClgLbl.text = clgUniq
}else{
cell.userClgLbl.text = ""
}
return cell
}
I hope you are persing response as Dictionary<String, Any>
Let me know if you are still having any issue.

Search JSON data in tableView swift4

I am trying to show jsondata in to the tableView and search country from the searchBar but getting error in to the textDidChange function.
I want the user to enter three words into the searchBar then tableView will open and search data.
struct country : Decodable {
let name : String
let capital : String
let region : String
}
class ViewController: UIViewController,UISearchBarDelegate {
var isSearch : Bool = false
var countries = [country]()
var arrFilter:[String] = []
#IBOutlet weak var tableview: UITableView!
#IBOutlet weak var searchbar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
tableview.dataSource = self
tableview.delegate = self
searchbar.delegate = self
let jsonurl = "https://restcountries.eu/rest/v2/all"
let url = URL(string: jsonurl)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do{
self.countries = try JSONDecoder().decode([country].self, from: data!)
}
catch{
print("Error")
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}.resume()
}
shows error into this part.
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count == 0 {
isSearch = false;
self.tableview.reloadData()
} else {
arrFilter = countries.filter({ (text) -> Bool in
let tmp: NSString = text
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
if(arrFilter.count == 0){
isSearch = false;
} else {
isSearch = true;
}
self.tableview.reloadData()
}
}
}
my table view part
extension ViewController : UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(isSearch){
return arrFilter.count
}
else{
return countries.coun
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(isSearch){
cell.textLabel?.text = arrFilter[indexPath.row]
}else{
cell.textLabel?.text = countries[indexPath.row].name.capitalized
}
return cell
}
}
First of all do not use NSString in Swift and the Foundation rangeOfString API, use native String and native range(of.
Second of all never check for an empty string and for an empty array with .count == 0. There is isEmpty.
Third of all please name structs and classes with a starting capital letter. struct Country ....
The error occurs because you are filtering Country instances and actually you are looking for its name or its region.
This is a pure Swift version of your code
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
isSearch = false
} else {
arrFilter = countries.filter( $0.name.range(of: searchText, options: .caseInsensitive) != nil }
isSearch = !arrFilter.isEmpty
}
self.tableview.reloadData()
}
If you want to filter for name and region write
arrFilter = countries.filter( $0.name.range(of: searchText, options: .caseInsensitive) != nil
|| $0.region.range(of: searchText, options: .caseInsensitive) != nil }
With this syntax declare arrFilter
var arrFilter = [Country]()
and in cellForRow write
let dataArray = isSearch ? arrFilter : countries
cell.textLabel?.text = dataArray[indexPath.row].name.capitalized
You are getting country object of your array as a string so such an error occured..
Please do as below
var arrFilter:[country] = [country]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(isSearch){
cell.textLabel?.text = arrFilter[indexPath.row].name.capitalized
}else{
cell.textLabel?.text = countries[indexPath.row].name.capitalized
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count == 0 {
isSearch = false;
self.tableview.reloadData()
} else {
arrFilter = countries.filter({ (country) -> Bool in
let tmp: NSString = NSString.init(string: country.name)
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(arrFilter.count == 0){
isSearch = false;
} else {
isSearch = true;
}
self.tableview.reloadData()
}
}
First you can not assign a value type [Country] to [String].For example when assign a arrFilter at that time country.filter always return country type value not a string type.
use below code to helping you,
var countries = [country]()
var arrFilter:[country] = [country]()
inside the viewdidLoad
override func viewDidLoad() {
self.countries.append(country(name: "India", capital: "New Delhi", region: "Asia"))
self.countries.append(country(name: "Indonesia", capital: "Jakarta", region: "region"))
self.countries.append(country(name: "Australia", capital: "Canberra", region: "Austrialia"))
// Do any additional setup after loading the view.
}
And
self.arrFilter = self.countries.filter({ (country) -> Bool in
let temp : NSString = country.name as NSString //or you can use country.capital or country.region
let range = temp.range(of: "ind", options: .caseInsensitive)
print(range.location)
print(range.length)
print(temp)
return range.location != NSNotFound
})
Thanks

TableView search bar issue (Swift - Firebase)

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

Accessing struct object array in no of rows in section returning null

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()
}
}
}

Resources