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

Posted

技术标签:

【中文标题】我正在尝试在我的应用程序中实现搜索栏,以便我可以搜索从 parse.com 检索到的对象【英文标题】:am trying to implement search bar in my app so that i can search the objects which are retrieved from parse.com 【发布时间】:2015-12-02 19:23:38 【问题描述】:
 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;

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

【问题讨论】:

你没有说什么不工作,也没有说涉及到代码的哪个特定部分 嘿@Wain 一切正常但不是搜索的东西我认为我没有使用 var data: = [PFobject] ,一切正常但是当我试图搜索它不会给我任何回报 shrikar.com/blog/2015/03/31/parse-search-in-ios-8-with-swift 试图实现本教程中的搜索功能 "className" 你真的有这样的课吗? 同时你在哪里使用self.data对象?你在 UITableView 中显示 noteObjects 【参考方案1】:

您可以使用 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 )




 

【讨论】:

以上是关于我正在尝试在我的应用程序中实现搜索栏,以便我可以搜索从 parse.com 检索到的对象的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中实现搜索栏

尝试实现搜索栏时出现 Swift 错误

如何解决在离子3中实现搜索栏的管道时出现的错误(管道搜索找不到或未找到)

Flutter - 实现 listView 搜索功能

我的搜索栏中的文本字段不允许输入文本(swiftUI)

尝试在我的项目中实现没有 Symfony2 的 Twig 和 Assetic