Swift - 搜索始终在全文之前执行

时间:2016-02-08 14:42:03

标签: ios swift firebase

我有一个类来处理用户通过用户名寻找另一个用户。外观部分通过SearchBar控件完成。后端是Firebase。

以下是我的完整代码:

class AddFriendByUsernameTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {

    /**************************Global Variables************************/
    var friendObject = FriendClass()
    var friendsArray = [FriendClass]()
    var friendsUsernames = [String]()
    var isFirstLoading: Bool = true
    var utiltiies = Utilities()
    var searchActive : Bool = false
    var usernames:[String]!
    /**************************UI Components************************/
    @IBOutlet weak var searchBar: UISearchBar!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchBar.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func search(searchText: String? = nil){

        /****************************Get Username by Auth Data****************************/
        if(searchText != nil)
        {
            self.getAllUsersForSearchFilter({(result) -> Void in
                if(result.domain == "")
                {
                    let containsResult = self.usernames.contains(searchText!)
                    if(containsResult == true)
                    {
                        /*Query All information for found username*/
                        let reference = Firebase(url:"https://something.firebaseio.com/users/")
                        /****************************Get Username by Auth Data****************************/
                        reference.queryEqualToValue(searchText!).observeEventType(.Value, withBlock: { (snapshot: FDataSnapshot!) -> Void in

                            for userInstance in snapshot.children.allObjects as! [FDataSnapshot]{

                            }
                        })



                    }else{
                        print("No matching username to search Text")
                    }
                }
            })
        }


    }


    func getAllUsersForSearchFilter(completion: (result: NSError) -> Void)
    {
        let errorFound:NSError = NSError(domain: "", code: 0, userInfo: nil)

        let reference = Firebase(url:"https://something.firebaseio.com/users/")
        reference.observeEventType(.Value, withBlock: { (snapshot: FDataSnapshot!) -> Void in
            if(snapshot != nil )
            {
                for userInstance in snapshot.children.allObjects as! [FDataSnapshot]{
                    //username = (userInstance.value["username"] as? String)!
                    //self.usernames.append(userInstance.value["username"] as! String)
                }
                completion(result: errorFound)
            }else{
                completion(result: errorFound)
            }

        })
    }


    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows

        if(usernames != nil)
        {
            return usernames.count
        }
        return 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell


        //self.tempObjectHolder = self.data[indexPath.row]
        //cell.textLabel!.text = self.tempObjectHolder["appUsername"] as? String


        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let indexPathT = tableView.indexPathForSelectedRow;
        let currentCell = tableView.cellForRowAtIndexPath(indexPathT!)

        /*Get username selected from the search results. */
        self.friendObject.username = currentCell?.textLabel!.text

        /*self.friendObject.name = self.tempObjectHolder["name"] as? String
        self.friendObject.mobile = self.tempObjectHolder["mobile"] as? String
        self.friendObject.telephone = self.tempObjectHolder["telephone"] as? String
        self.friendObject.username = self.tempObjectHolder["appUsername"] as? String
        self.friendObject.email = self.tempObjectHolder["email"] as? String
        self.friendObject.workAddressString = self.tempObjectHolder["workAddress"] as! String
        self.friendObject.homeAddressString = self.tempObjectHolder["homeAddress"] as! String*/

        self.performSegueWithIdentifier("viewUserResultsSegue", sender: self)

    }

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchActive = true;
    }

    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchActive = false;
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        search()
        searchActive = false;
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        search(searchText)
    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "viewUserResultsSegue") {
            // pass data to next view
            //let destinationVC = segue.destinationViewController as! ViewResultUserProfileViewController
            //destinationVC.friendObject = self.friendObject;

        }
    }
}

当我开始在搜索栏中输入时,它会执行并触发错误:

致命错误:在解包可选值时意外发现nil

这种情况正在发生,因为它花了我输入的第一个字符并搜索它。我想要它搜索完整的工作(用户名)而不是第一封信。

谢谢,

1 个答案:

答案 0 :(得分:2)

要点击键盘Enter时执行某些操作,您可以在视图控制器中创建IBAction方法,例如:

@IBAction func enterDetected(sender: UITextField) {
    print("Saw an 'Enter'")
}

然后连接UITextField"触发的主要操作"连接到Interface Builder中的方法。