从Parse获取数组到表视图(Swift 2)

时间:2016-01-23 03:51:33

标签: ios swift parse-platform

我正在尝试在Parse的“User”类中的“my_classes”中提取一个字符串数组。当我点击搜索按钮时,我希望数组中的每个单独的字符串成为tableview中的单独单元格。这是我在“my_classes”中的数组:[“物理”,“经济学”,“前微积分”]。我想要“物理学”作为自己的细胞,“经济学”作为自己的细胞等等。

import UIKit
import Parse

class CardSetClassTableViewController: UITableViewController, UISearchBarDelegate {

    // MARK: Outlets

    @IBOutlet var searchBar: UISearchBar!

    @IBOutlet var resultsTableView: UITableView!


    // MARK: Variables

    var searchResults = [String]()


    // MARK: Actions

    @IBAction func newClassBarButtonItemPressed(sender: AnyObject) {

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

    }



    // MARK: Functions

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchBar.delegate = self

    }

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

    func displayAlert(title: String, message: String) {

        let alert = UIAlertController(title: title, message: message, preferredStyle:UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)

    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar)
    {

        if reachabilityStatus == kNOTREACHABLE {

            self.displayAlert("No Internet Connection", message: "Please connect to the internet before continuing.")

        } else {

            searchBar.resignFirstResponder()
            print("Search word = \(searchBar.text!)")

            let classNameQuery = PFQuery(className:"_User")
            classNameQuery.whereKey("my_classes".lowercaseString, equalTo: searchBar.text!.lowercaseString)


            let query = PFQuery.orQueryWithSubqueries([classNameQuery])



            query.findObjectsInBackgroundWithBlock {
                (results: [PFObject]?, error: NSError?) -> Void in

                if error != nil {

                   self.displayAlert("Error", message: error!.localizedDescription)

                    return
                }

                if let objects = results {

                    self.searchResults.removeAll(keepCapacity: false)

                    for object in objects {

                        let className = object.valueForKey("my_classes") as! String


                        self.searchResults.append(className)


                    }

                    dispatch_async(dispatch_get_main_queue()) {
                        self.resultsTableView.reloadData()
                        self.searchBar.resignFirstResponder()

                    }



                }




            }



        }

    }


    // MARK: - Table view data source



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

        return searchResults.count
    }


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


        cell.textLabel!.text = searchResults[indexPath.row]

        return cell

    }

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



        let classIndexPath = tableView.indexPathForSelectedRow!

        let selectedCell = tableView.cellForRowAtIndexPath(classIndexPath)! as UITableViewCell

        let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.labelText = "Loading"



        if reachabilityStatus == kNOTREACHABLE {

            spinningActivity.hide(true)

            self.displayAlert("No Internet Connection", message: "Please connect to the internet before continuing.")


        } else {

            // let className : String = String(selectedCell.textLabel!.text!)

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

        }


        searchBar.resignFirstResponder()
    }

}

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试以下方法......

修改

 var songsArray = [String]()

 func fetchUsers() {
let userQuery: PFQuery = PFUser.query()!

//search users by the sepcified username, returns a users! object
//make an array to put the values from the users! array object into
//then append those from your "middle-man" array into your destination array,     
//in this example songArray is destination array and songsFromParse is "middle-man" array

userQuery.whereKey("username", equalTo: (username)!)
userQuery.findObjectsInBackgroundWithBlock({
    (users, error) -> Void in

    var songsFromParse = users!

    if error == nil {
        if songsFromParse.count != 0 {

      self.songsArray = (songsFromParse[i].valueForKey("CurrentSongURLArray") as! Array)
            }


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

然后,获取包含您检索到的对象的新数组,在此示例中为songsArray,并使用它来填充tableView。在cellForRowAtIndexPath ...

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("Cell ID")
cell?.textLabel?.text = songsArray[indexPath]
return cell!
}