我正在尝试使用我的应用程序中的UISearchBar来搜索我的Firebase数据,但我被卡住了。我已在表格视图中成功从Firebase接收数据。我希望用户成为一个通过releaseName和/或releaseType搜索“发布”的人。
Firebase数据结构
视图控制器
import UIKit
import FirebaseDatabase
import SDWebImage
import SwiftyGif
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, SwiftyGifDelegate {
var refReleases: DatabaseReference!
var releasesData = [ReleaseModel]()
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ReleaseCell", for: indexPath) as! ReleaseTableViewCell
var release: ReleaseModel
release = releasesData[indexPath.row]
cell.releaseType.text = release.releasetype
cell.releaseName.text = release.releasename
cell.releasePrice.text = release.releaseprice
cell.releaseDate.text = release.releasedate
cell.releaseImage.sd_setImage(with: URL(string: release.releaseimage!), placeholderImage: UIImage(named: "placeholder1"))
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return releasesData.count
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let release = releasesData[indexPath.row]
performSegue(withIdentifier: "ReleasesToWebviews", sender: release)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var wbVC: WebviewsViewController = segue.destination as! WebviewsViewController
}
override func viewDidLoad() {
super.viewDidLoad()
allButton.setImage(UIImage(named:"selectedall"), for: .normal)
searchBarController.searchResultsUpdater = self
searchBarController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
view.addSubview(logoAnimationView)
logoAnimationView.pinEdgesToSuperView()
logoAnimationView.logoGifImageView.delegate = self
// Remove title from back button. Now only "<" symbol will be show as back button.
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = backButton
// Do any additional setup after loading the view, typically from a nib.
//Search bar
self.navigationItem.searchController = searchBarController
navigationItem.hidesSearchBarWhenScrolling = false
searchBarController.searchBar.tintColor = UIColor.white
searchBarController.searchBar.barTintColor = UIColor.white
let placeholderAppearance = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
placeholderAppearance.font = UIFont(name: "Avenir", size: 16)
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search for brand, color, etc.", attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange])
if let textfield = searchBarController.searchBar.value(forKey: "searchField") as? UITextField {
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
//Retrieving data from Firebase
refReleases = Database.database().reference().child("releases");
refReleases.observe(DataEventType.value) { (snapshot) in
if snapshot.childrenCount>0{
self.releasesData.removeAll()
for releases in snapshot.children.allObjects as![DataSnapshot]{
let releaseObject = releases.value as? [String: AnyObject]
let releaseName = releaseObject?["releaseName"]
let releaseType = releaseObject?["releaseType"]
let releasePrice = releaseObject?["releasePrice"]
let releaseDate = releaseObject?["releaseDate"]
let releaseImage = releaseObject?["releaseImage"]
let release = ReleaseModel(releasetype: releaseType as! String?, releasename: releaseName as! String?, releaseprice: releasePrice as! String?, releasedate: releaseDate as! String?, releaseimage: releaseImage as! String?)
self.releasesData.append(release)
}
self.tableView.reloadData()
}
}
}
ReleaseModel.swift
class ReleaseModel: NSObject{
var releasetype: String?
var releasename: String?
var releaseprice: String?
var releasedate: String?
var releaseimage: String?
init(releasetype:String?, releasename:String?, releaseprice:String?, releasedate:String?, releaseimage:String?) {
self.releasetype = releasetype
self.releasename = releasename
self.releaseprice = releaseprice
self.releasedate = releasedate
self.releaseimage = releaseimage
}
}
ReleaseTableViewCell.swift
import UIKit
import OneSignal
class ReleaseTableViewCell: UITableViewCell {
@IBOutlet weak var releaseType: UILabel!
@IBOutlet weak var releaseName: UILabel!
@IBOutlet weak var releasePrice: UILabel!
@IBOutlet weak var releaseDate: UILabel!
@IBOutlet weak var releaseImage: UIImageView!
@IBOutlet weak var notifyButton: UIButton!
@IBAction func tapButton(_ sender: UIButton) {
// Call when you want to prompt the user to accept push notifications.
// Only call once and only if you set kOSSettingsKeyAutoPrompt in AppDelegate to false.
OneSignal.promptForPushNotifications(userResponse: { accepted in
print("User accepted notifications: \(accepted)")
})
sender.isSelected = !sender.isSelected
UserDefaults.standard.set(sender.isSelected, forKey: "isSaved")
if (UserDefaults.standard.bool(forKey: "isSaved") == sender.isSelected) {
OneSignal.sendTag("notificationtest", value: "true")
}
OneSignal.deleteTag("notificationtest")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//Set button image
notifyButton.setImage(UIImage(named: "notifybutton"), for: .normal)
notifyButton.setImage(UIImage(named: "notifiedbutton"), for: .selected)
notifyButton.isSelected = UserDefaults.standard.bool(forKey: "isSaved")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}