1

I am trying to pull an array of strings in the from "my_classes" in the "User" class in Parse. I want each individual string within the array to become a separate cell in a tableview when I tap on the search button. This is my array in "my_classes" : ["Physics","Economics","Pre Calculus"]. I want "Physics" as it's own cell, "Economics" as its own cell, etc.


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()
    }

}

Thanks!

1 Answer 1

1

Try the following...

Edit

 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)
    }
 })
}

You then take your new array that contains the objects that you retrieved, in this example songsArray and use it to populate your tableView. In cellForRowAtIndexPath ...

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

let cell = tableView.dequeueReusableCellWithIdentifier("Cell ID")
cell?.textLabel?.text = songsArray[indexPath]
return cell!
}
Sign up to request clarification or add additional context in comments.

3 Comments

p.s if this worked for you, please check off and accept answer :)
It looks like you are trying to get a query of songs from each user. I am trying to pull an array of strings from "my_classes" from only one user.
Oh ok i see, I just edited my answer. Now you search by a specified username and then retrieve the [Array] that you want by specifying its valueForKey which is whatever you named the column in Parse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.