简体   繁体   English

搜索和过滤数组Firebase数据swift3

[英]searching and filter array firebase data swift3

My app crashing while search a text in a searchbar with error: thread1:signal SIGABRT probably the problem updateSearchResults() method? 我的应用程序在搜索栏中搜索错误时出错,该文本出现错误:thread1:signal SIGABRT可能是问题updateSearchResults()方法? or type of array? 或数组类型? I'm beginner with swift any idea? 我是个初学者,有什么想法吗?

@IBOutlet weak var tableView: UITableView!

var data = [Any]()
var ref:FIRDatabaseReference!

// Filter Data from Firebase
var filteredData = [Any]()

// Declare searchBar

let searchController = UISearchController(searchResultsController: nil)


//is the device landscape or portrait
var isPortraid = true

@IBOutlet weak var bannerView: GADBannerView!



func fetchDataFromFirebase(){
    EZLoadingActivity.show("caricamento...", disableUI: true)
    ref = FIRDatabase.database().reference()
    ref.observe(.value, with: { (snapshot) in
        let dataDict = snapshot.value as! NSDictionary
        self.data = dataDict["data"] as! [Any]
        self.filteredData = self.data
        print ("Sacco di merda:\(self.filteredData)")
        self.tableView.reloadData()
        EZLoadingActivity.hide()
    })
}



override func viewDidLoad() {
    super.viewDidLoad()


    tableView.delegate = self
    fetchDataFromFirebase()

    //  Implement searchBar
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar




    NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)


}


//TableView Data Source and Delegate


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}


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

    return filteredData.count
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for:indexPath) as! MainScreenTableViewCell
    let rowData = self.filteredData[indexPath.row] as! NSDictionary
    let imageName  = rowData["imageName"] as! String
    cell.backgroundImageView.image = UIImage(named: imageName)

    let label = rowData["categoryName"] as! String
    cell.mealCategoryLabel.text = label
    return cell
}



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let categoryViewController = storyboard.instantiateViewController(withIdentifier: "CategoryViewController") as! CategoryViewController
    let rowData = self.data[indexPath.row] as! NSDictionary
    categoryViewController.categoryTitle = rowData["categoryName"] as! String
    let categoryData = rowData["category"] as! [Any]
    categoryViewController.data = categoryData
    self.navigationController?.pushViewController(categoryViewController, animated: true)

}





func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isPortraid {
    return UIScreen.main.bounds.height/3
    } else {
        return UIScreen.main.bounds.height/1.2
    }
}

//Method for update search //更新搜索方法

func updateSearchResults(for searchController: UISearchController) {
    if searchController.searchBar.text! == ""{
        filteredData = data
    } else {
        filteredData = data.filter{($0 as AnyObject).contains(searchController.searchBar.text!)}

    }
    self.tableView.reloadData()
}
if searchController.searchBar.text! == ""

This is almost certainly the offender. 这几乎可以肯定是罪犯。 The text property on UI objects is typically nil when it's empty, so when you force unwrap it your app crashes. UI对象的text属性为空时,通常为nil,因此,当您强制展开它时,应用程序崩溃。 You should never force unwrap something unless you are absolutely certain it will never be nil at that point. 除非绝对确定在那时您永远不会将其包装成零,否则切勿强行打开包装。

There's a couple different ways you can handle this, which basically amount to making sure text isn't nil before you do anything with it. 您可以通过几种不同的方式来处理此问题,这基本上等于在执行任何操作之前确保text不为零。

Personally I would rewrite the if statement to unwrap the optional for the non-empty case: 就我个人而言,我将重写if语句以解开非空情况下的可选内容:

if let text = searchController.searchBar.text, text != "" {
    filteredData = data.filter{($0 as AnyObject).contains(text)}
} else {
    filteredData = data
}

You could also use nil-coalescing : 您还可以使用nil-coalescing

if (searchController.searchBar.text ?? "") == ""

but personally I prefer to write it to avoid force unwrapping even when you're sure it isn't nil, so I would recommend the first one. 但就我个人而言,我更喜欢编写它来避免强制展开,即使您确定它不是nil,所以我推荐第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM