iosswiftparse-platformlocal-datastore

Swift Parse - local datastore and displaying objects in a tableview


I am building and app that saves an object in the local datastore with parse. I then run a query to retrieve the objects that are in the local datastore and it is working fine. however, I would like to grab the object, and the contents in it, and set some labels in a table view cell based on the items that are stored in the parse local data store object. for example, i make an object with attributes like "objectID", "name", "date", "location". what i'd like to do is to have a table view on the home screen that displays the name, date, location ...etc. of each item that was saved in local datastore in labels in each cell.

i know that im saving it correctly:

// parse location object

    let parseLighthouse = PFObject(className: "ParseLighthouse")
    parseLighthouse.setObject(PFUser.currentUser()!, forKey: "User")
            parseLighthouse["Name"] = self.placeTitle.text
            parseLighthouse["Note"] = self.placeNote.text
            parseLighthouse["Locality"] = self.placeDisplay.text!
            parseLighthouse["Latt"] = self.map.region.center.latitude
            parseLighthouse["Longi"] = self.map.region.center.longitude
            parseLighthouse["LattDelta"] = 0.5
            parseLighthouse["LongiDelta"] = 0.5
            parseLighthouse["Date"] = dateInFormat
            parseLighthouse.pinInBackground()
            parseLighthouse.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
                println("Object has been saved. ID = \(parseLighthouse.objectId)")
            }

and when i run the query, im able to access the attributes by running println(object.objectForKey("Name"))

func performQuery() {
    let query = PFQuery(className: "ParseLighthouse")

    query.fromLocalDatastore()
    query.whereKey("User", equalTo: PFUser.currentUser()!)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            // The find succeeded.
            println("Successfully retrieved \(objects!.count) lighthouses.")
            // Do something with the found objects
            if let light = objects as? [PFObject] {
                for object in light {
                    println(object.objectId)
                    println(object.objectForKey("Name"))



                }
            }
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
    }

because when running the query, i get back the object id and name as expected.

Successfully retrieved 2 lighthouses. Optional("A3OROVAMIj") Optional(happy) Optional("bbyqPZDg8W") Optional(date test)

what I would like to do is grab the name field within the parse object local data store, and that be the name of the label on a cell in a table view controller.

i dont know how to access that info from the object, and set the label correctly.

does anyone know how this is possible?


Solution

  • It's always a good idea to avoid pointer lol ... so why not saving the userid or username with the specific object.. so change this line:

     parseLighthouse.setObject(PFUser.currentUser()!, forKey: "User")
    

    TO

     parseLighthouse["username"] = PFUser.currentUser().username
    

    Answer

    NOW let's create a struct that contains the objectID and the Name outside of your Controller Class.

    struct Data
    {
    var Name:String!
    var id:String!
    }
    

    then inside of the Controller class, declare the following line of code globally

     var ArrayToPopulateCells = [Data]()
    

    Then your query function will look like :

     func performQuery() {
        let query = PFQuery(className: "ParseLighthouse")
    
        query.fromLocalDatastore()
        query.whereKey("User", equalTo: PFUser.currentUser()!)
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if error == nil {
                // The find succeeded.
                print("Successfully retrieved \(objects!.count) lighthouses.")
                // Do something with the found objects
                if let light = objects as? [PFObject] {
                    for object in light {
                        print(object.objectId)
                        print(object.objectForKey("Name"))
                        var singleData = Data()
                        singleData.id = object.objectId
                        singleData.Name = object["Name"] as! String
    
                        self.ArrayToPopulateCells.append(singleData)
    
    
                    }
                }
            } else {
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
    

    In the tableView numberOfRowinSection()

    return ArrayToPopulateCells.count
    

    In the cellForRowAtIndexPath()

           var data = ArrayToPopulateCells[indexPath.row]
           cell.textlabel.text = data.objectID
           cell.detailLabel.text = data.Name
    

    VOila that should be it