ios - 我正在尝试在我的应用程序中实现搜索栏,以便我可以搜索从 parse.com 检索到的对象

标签 ios swift parse-platform

 import UIKit

 class MasterTableViewController: UITableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate {

@IBOutlet var searchBar: UISearchBar!


// creating array for holding ojects 



var noteObjects: NSMutableArray! = NSMutableArray()
  var v = 0

var searchActive : Bool = false
var data:[PFObject]!
var filtered:[PFObject]!


override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.delegate = self

}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)



    if v == 0 {
        self.fetchAllObjectsFromLocalDataStore()
        //self.fetchAllObjects()

    }
}


// fetching data from local datastrore and from parse

func fetchAllObjectsFromLocalDataStore(){

    let query: PFQuery = PFQuery(className: "className")
    query.orderByDescending("createdAt")


    query.fromLocalDatastore()

    query.findObjectsInBackgroundWithBlock { (var objects, error) -> Void in
        self.search()
        if (error == nil) {




            let temp: NSArray = objects as! NSArray

            self.noteObjects = temp.mutableCopy() as! NSMutableArray
           self.search()
             self.tableView.reloadData()


        }else {
        print(error!.userInfo)

        }
    }

}



func fetchAllObjects(){

   let query: PFQuery = PFQuery(className: "className")
    query.orderByDescending("createdAt")

  search()
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil) {




            PFObject.pinAllInBackground(objects, block:  nil )


            self.fetchAllObjectsFromLocalDataStore()

           // self.tableView.reloadData()


        } else {
        print(error?.userInfo)

        }
 }
}





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



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

    return self.noteObjects.count
}


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

 let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject



    cell.MasterTitleLabel?.text = object["Title"] as? String
    cell.MasterTextLabel.text = object["Fstory"] as? String
    cell.MasterTimeLabel.text = object["Time"] as? String
    cell.MasterLocationLabel.text = object["Location"] as? String



    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("openStory", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let upcoming: AddNoteTableViewController = segue.destinationViewController as! AddNoteTableViewController

    if (segue.identifier == "openStory"){


        let indexPath = self.tableView.indexPathForSelectedRow!

        let object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject

        upcoming.object = object

        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

}


@IBAction func btnReload(sender: AnyObject) {

    fetchAllObjects()
  }


override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
  }
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete ){

        let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        // the below for deleting the selected cell's object from server's database
       // object.deleteInBackground()

        //the below for deleting the selected cell's object from localstorage
        object.unpinInBackground()


      self.noteObjects.removeObjectAtIndex(indexPath.row)
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

  }
}





func search(searchText: String? = nil){
    let query = PFQuery(className: "className")
    if(searchText != nil){
        query.whereKey("Title", containsString: searchText)
    }
    query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
        self.data = results! as [PFObject]
        self.tableView.reloadData()
    }
}

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

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

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

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

上面的代码用于检索解析的对象并实现搜索栏,以便我可以通过搜索功能搜索我的对象,但我不知道缺少什么或如何正确处理它,如果有人知道请帮助我

最佳答案

你可以使用 UIsearchBar 尝试这样的事情

class TableViewController: UITableViewController, UISearchBarDelegate {


 @IBOutlet var searchBar: UISearchBar!
 var userList:NSMutableArray = NSMutableArray()


var noteObjects: NSMutableArray = NSMutableArray()




override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.delegate = self

        self.fetchAllObjectsFromLocalDataStore()






}


func loadUsers(name:String){
    var findUsers:PFQuery = PFUser.query()!

    if !name.isEmpty{
        findUsers.whereKey("username", containsString: name)
        findUsers.whereKey("username", containsString: name .lowercaseString)

        let user = PFUser.currentUser()

        if let user = PFUser.currentUser() {
            findUsers.whereKey("institute", equalTo: user["institute"])
        }
    }
           findUsers.fromLocalDatastore()

  findUsers.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in

                if (error == nil) {

                               self.userList = NSMutableArray(array: objects!)

                                 self.tableView.reloadData()
             }else {
                    print(error!.userInfo)

   }
    }}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    loadUsers(searchText)
 self.searchBar.setShowsCancelButton(true, animated: true)

}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    loadUsers("")

    self.searchBar.setShowsCancelButton(false, animated: true)
    self.searchBar.endEditing(true)
}



// 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 searchBar.text == "" {

    return noteObjects.count
    } else {


        return userList.count }
        //self.noteObjects.count
}


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

    if searchBar.text == "" {


    let object : PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
        let photo: PFFile = object["photo"] as! PFFile

        photo.getDataInBackgroundWithBlock{
            (imageData:NSData?, error:NSError?)-> Void in

            if (error == nil){
                let image:UIImage = UIImage(data: imageData!)!
                cell.imgViewUser.image = image
            }
            else if error != nil{
                print("error")
            }
         }


        cell.lblUserInterest.text = object["interest"] as? String
        //cell.imgViewUser.image = object["photo"]  as? PFFile
        cell.lblUsername.text  = object["username"] as? String
      return cell
    } else  {

    let object : PFObject = self.userList.objectAtIndex(indexPath.row) as! PFObject



    let photo: PFFile = object["photo"] as! PFFile

    photo.getDataInBackgroundWithBlock{
        (imageData:NSData?, error:NSError?)-> Void in

        if (error == nil){
            let image:UIImage = UIImage(data: imageData!)!
            cell.imgViewUser.image = image
        }
        else if error != nil{
            print("error")
        }}
      cell.lblUserInterest.text = object["interest"] as? String
    //cell.imgViewUser.image = object["photo"]  as? PFFile

    cell.lblUsername.text  = object["username"] as? String



  return cell
    }


}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var object :AnyObject?


}






override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete ){




 }

关于ios - 我正在尝试在我的应用程序中实现搜索栏,以便我可以搜索从 parse.com 检索到的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051242/

相关文章:

ios - Firebase 更新后如何阻止 UICollectionView 显示重复项目

iOS 6.1 Safari 没有设置接受编码

javascript - 解析API请求计数和批处理: saveAll() destroyAll() etc

ios - Swift & Parse - PFUser currentUser 从不等于 nil

ios - 使用 Storyboard自定义 Unity3D Xcode 项目

objective-c - 以编程方式创建布局约束

android - Firebase Crashlytics 有替代品吗?

ios - 确定排序后数组是否发生变化

swift - Audiokit 修剪音频

android - 如何在单个应用程序中实现多个 GCM 推送通知?