Parse Objects not retrieved nor presented in UITableView - ios

I am querying parse objects from a relation pointer, and then presenting those objects in a UITableview. However, whenever I use my code to query nothing shows up and it is just blank. I have used this code before to query objects from parse but not from a relation. Any help on how to query it and present it would greatly be appreciated.
class MyGroupsHomePage: UITableViewController {
let cellidentifer = "MyGroupsCell"
var mygroupsdata: NSMutableArray = NSMutableArray()
func findcurrentuserobjects () {
var currentuser = PFUser.query()
currentuser!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
currentuser!.findObjectsInBackgroundWithBlock { (object:[AnyObject]?, error: NSError?) -> Void in
if error == nil && object != nil {
if let object = object as? [PFObject] {
for objects in object {
let relation = objects.relationForKey("UserGroups")
let query = relation.query()
query?.findObjectsInBackgroundWithBlock({ (ob: [AnyObject]?, er: NSError?) -> Void in
if er == nil && ob != nil {
if let ob = ob as? [PFObject] {
for obs in ob {
self.mygroupsdata.addObject(obs)
}
}
}
})
}
}
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
findcurrentuserobjects()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mygroupsdata.count
}
The GroupName object represents the column of objects I want to retrieve from the relation.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellidentifer, forIndexPath: indexPath) as! UITableViewCell
let mygroupdata: PFObject = self.mygroupsdata.objectAtIndex(indexPath.row) as! PFObject
cell.textLabel?.text = mygroupdata.objectForKey("GroupName")! as? String
return cell
}

When you call self.tableView.reloadData() there is no data added to mygroupsdata yet, because query?.findObjectsInBackgroundWithBlock is an asynchronous function that returns immediately. The callback that adds objects to mygroupsdata is excuted after you reload the tableview. Try to reload the tableview here:
query?.findObjectsInBackgroundWithBlock({ (ob: [AnyObject]?, er: NSError?) -> Void in
if er == nil && ob != nil {
if let ob = ob as? [PFObject] {
for obs in ob {
self.mygroupsdata.addObject(obs)
}
}
self.tableView.reloadData()
}
})

Related

trying to implement the uisearchcontroller but its not giving any search result

import UIKit
class MasterTableViewController: UITableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
//approches for uisearchbar
var searchNotes: [PFObject] = [PFObject]()
var notesSearchController = UISearchController()
var searchActive: Bool = false
// creating array for holding ojects
var noteObjects: NSMutableArray! = NSMutableArray()
var v = 0
override func viewDidLoad() {
super.viewDidLoad()
self.notesSearchController = UISearchController(searchResultsController: nil)
self.notesSearchController.dimsBackgroundDuringPresentation = true
self.notesSearchController.searchResultsUpdater = self
// Configure the search controller's search bar
self.notesSearchController.searchBar.placeholder = "Search for a user"
self.notesSearchController.searchBar.sizeToFit()
self.notesSearchController.searchBar.delegate = self
self.definesPresentationContext = true
// Set the search controller to the header of the table
self.tableView.tableHeaderView = self.notesSearchController.searchBar
print("check")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if v == 0 {
self.fetchAllObjectsFromLocalDataStore()
//self.fetchAllObjects()
}
}
// fetching data from local datastore and from parse
func fetchAllObjectsFromLocalDataStore(){
let query: PFQuery = PFQuery(className: "Sinhgad")
query.orderByDescending("createdAt")
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in
if (error == nil) {
let temp: NSArray = objects as NSArray!
self.noteObjects = temp.mutableCopy() as! NSMutableArray
self.tableView.reloadData()
}else {
print(error!.userInfo)
}
}
}
func fetchAllObjects(){
let query: PFQuery = PFQuery(className: "Sinhgad")
query.orderByDescending("createdAt")
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
if (self.notesSearchController.active) {
return self.searchNotes.count
} else {
return self.noteObjects.count
}}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MasterTableViewCell
if (self.notesSearchController.active && self.searchNotes.count > indexPath.row) {
// bind data to the search results cell
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
} else {
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) {
if (self.notesSearchController.active && self.searchNotes.count > 0) {
// Segue or whatever you want
self.performSegueWithIdentifier("openStory", sender: self)
} else {
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)
}
}
// MARK: - Parse Backend methods
func loadSearchUsers(searchString: String) {
let query: PFQuery = PFQuery(className: "Sinhgad")
query.orderByDescending("createdAt")
// Filter by search string
query.whereKey("Notes", containsString: searchString)
self.searchActive = true
query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in
if (error == nil) {
self.searchNotes.removeAll(keepCapacity: false)
self.searchNotes += objects as [PFObject]!
self.tableView.reloadData()
} else {
// Log details of the failure
print("search query error: \(error) \(error!.userInfo)")
}
self.searchActive = false
}
}
// MARK: - Search Bar Delegate Methods
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// Force search if user pushes button
let searchString: String = searchBar.text!.lowercaseString
if (searchString != "") {
loadSearchUsers(searchString)
}
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Force reload of table data from normal data source
}
// MARK: - UISearchResultsUpdating Methods
// This function is used along with UISearchResultsUpdating for dynamic search results processing
// Called anytime the search bar text is changed
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString: String = searchController.searchBar.text!.lowercaseString
if (searchString != "" && !self.searchActive) {
loadSearchUsers(searchString)
}
}
}
The above code is for retrieving stored objects from parse's server and from local storage and show them in table view.
Everything is working fine but I am trying to implement searchbar for adding searching function into my app. The problem is that when am running the app its showing the searchbar but when interacting with search bar its moving to upside and disappearing and when am typing anything.
I am not getting any search result and in NSLog am getting this :
2015-12-03 16:43:48.769 Notes[1015:56944] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UISearchController: 0x7ff2d48165a0>)
I know am missing something and its not the right way to achieve that function.
If somebody knows how to do it correctly or what am missing than please let me know , thanks and sorry if the way am asking question is not proper !
i just figured out that my 'searchNotes' var of Pfobject have nothing i mean its empty ! for that i tried
cell.MasterTitleLabel?.text = searchNotes["Title"] as! String
but its giving error
cannot subscript a value of type '[PFObject]' with an index of type 'string'
i know its because i declared searchNotes as
searchNotes [PFObject] = [PFObject]()
i should do it something like
searchNotes PFObject = PFObject()
but when am doing this its giving so many errors please help if somebody's know how to fix this
Maybe you shouldn't user PFObject directly.
Can you use another class instead of PFObject
private class object {
var mTitle : String!
var mStory : String!
var mTime : String!
var mLocation : String!
}
And use your code here
let obj : object = object()
obj.mTitle = PFObject["title"];
...etc

parse swift - unpin an item in table view cell

i would like to unpin an item that is in my tableview cell from parse. I save the object on another page, and query it in the main page, add that object to an array so it can be displayed in the table view. Now im not sure how to correctly select the corresponding parse object with whats in the array so that i can unpin it.
ideally i'd like to do this using the objectId just in case a user saves an object with the same name. how can i grab the objectId of whats displaying in my cell, and unpin it?
what query i use to add my objects to the array to then be displayed in my table view
var selectedLighthouse: localData? = nil
var arrayToPopulateCells = [localData]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
//query
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 lighthouse = objects {
self.arrayToPopulateCells.removeAll(keepCapacity: true)
for object in lighthouse {
var singleData = localData()
singleData.name = object["Name"] as! String
singleData.note = object["Note"] as! String
singleData.date = object["Date"] as! String
singleData.latt = object["Latt"] as! NSNumber
singleData.longi = object["Longi"] as! NSNumber
singleData.lattDelta = object["LattDelta"] as! NSNumber
singleData.longiDelta = object["LongiDelta"] as! NSNumber
singleData.locality = object["Locality"] as! String
self.arrayToPopulateCells.append(singleData)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
//setting table view datasource and delegate.
self.tableView.dataSource = self
self.tableView.delegate = self
var currentUser = PFUser.currentUser()
println(currentUser)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// var lighthouse = self.lighthouses[indexPath.row]
var data = self.arrayToPopulateCells[indexPath.row]
//setting the prototype cell to link with the identifier set in attributes earlier.
let cell = tableView.dequeueReusableCellWithIdentifier("locationCell") as! lighthouseCell
let row = indexPath.row
cell.cellName.text = data.name
cell.cellPlace.text = data.locality
// cell.cellCoordinates.text = "\(lighthouse.latt)" + ", " + "\(lighthouse.longi)"
// cell.cellNote.text = lighthouse.note
cell.cellDate.text = "\(data.date)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedLighthouse = self.arrayToPopulateCells[indexPath.row]
self.performSegueWithIdentifier("lighthouseDetailViewSegue", sender: self)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
var arrayObjectId = localData()
var queryLocal = PFQuery(className:"ParseLighthouse")
queryLocal.fromLocalDatastore()
queryLocal.whereKey("Name", equalTo: arrayObjectId.name)
queryLocal.getObjectInBackgroundWithId(arrayObjectId.name) {
(parseLighthouse: PFObject?, error: NSError?) -> Void in
if error == nil && parseLighthouse != nil {
parseLighthouse?.unpinInBackground()
} else {
println(error)
}
}
self.arrayToPopulateCells.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
In the commitediting() method you don't need to query again because your array already has all the data from parse so you just need to delete straight from the array then reloadData().
You just need:
if (editingStyle == UITableViewCellEditingStyle.Delete)
{
var object:PFObject = self.arrayToPopulateCells[indexPath.row] as! PFObject
object.deleteInBackgroundWithBlock() // so check the if error == nil
self.arrayToPopulateCells.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.reloadData()
}

All Parse Objects Not Presented in UITableView

I am retrieving objects from a relation in parse. The objects I want are successfully retrieved and printed in the output box, but when I run the app my UITable only presents one of the six objects. Any suggestions on how to get all of them up onto my view? I would greatly appreciate it.
class MyGroupsHomePage: UITableViewController {
let cellidentifer = "MyGroupsCell"
var mygroupsdata: NSMutableArray = NSMutableArray()
func findcurrentuserobjects () {
var currentuser = PFUser.query()
currentuser!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
currentuser!.findObjectsInBackgroundWithBlock { (object:[AnyObject]?, error: NSError?) -> Void in
if error == nil && object != nil {
if let object = object as? [PFObject] {
for objects in object {
self.mygroupsdata.addObject(objects)
}
}
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
findcurrentuserobjects()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mygroupsdata.count
}
var groupnamearray: NSMutableArray = NSMutableArray()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellidentifer, forIndexPath: indexPath) as! UITableViewCell
let mygroupdata: PFObject = self.mygroupsdata.objectAtIndex(indexPath.row) as! PFObject
let relation = mygroupdata.relationForKey("UserGroups")
let query = relation.query()
query?.findObjectsInBackgroundWithBlock({ (objet:[AnyObject]?, erro: NSError?) -> Void in
if erro == nil && objet != nil {
if let objet = objet as? [PFObject] {
for objets in objet {
println(objets.objectForKey("GroupName")!)
cell.textLabel?.text = objets.objectForKey("GroupName")! as? String
}
}
} else {
println("Error, could not retrieve user groups \(erro)")
}
})
return cell
}
}
As Paulw11 stated, this is the problem:
for objets in objet {
println(objets.objectForKey("GroupName")!)
cell.textLabel?.text = objets.objectForKey("GroupName")! as? String
}
You keep updating the same property "text" in the same textLabel, which I assume is an IBOutlet in the UITableViewCell subclass that you use to define the apparence of your cell. Without knowing more of how you want this text to be layed out it it difficult to suggest an answer. A quick and dirty way could be (I haven't tested):
for objets in objet {
println(objets.objectForKey("GroupName")!)
let obj = objets.objectForKey("GroupName")! as? String
let newString = "\(obj) "
cell.textLabel?.text = "\(cell.textLabel?.text)\(newString)"
}
But, according to what you want to acheive, you might need to add subviews to your UITableViewCell subclass (either on your cell prototype in Storyboard or programmatically).

I can retrieve the information from parse, also I can print that array, but when I try to put those array element in tableviewcell nothing shows up

I can retrieve the information from parse, also I can print that array, but when I try to put those array element in table view cell nothing shows up
the array.count also return 4
I don't know why table cell is empty
import UIKit
import Parse
class friendsViewController: UITableViewController {
var user = PFUser.currentUser()
var friends = [String]()
var profileFile = [PFFile]()
var height : CGFloat = UIScreen.mainScreen().bounds.size.height
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
//friends
var query = PFQuery(className:"Requests")
//query.orderByDescending("requestBy")
query.whereKeyExists("requestTo")
query.whereKey("requestBy", equalTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Friends recieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object)
self.friends.append(object["requestTo"] as! String)
println(self.friends)
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
println(self.friends.count)
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return friends.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return (height/7)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell1 = tableView.dequeueReusableCellWithIdentifier("friendCell") as! friendsTableViewCell
myCell1.friendLabel.text = friends[indexPath.row]
return myCell1
}
}
friends is populared after the table view loads. After you've received your data, on the main thread, call tableView.reloadData().
When your block is finished, please call your table to reload data.
Fixed it...
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Friends recieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object)
self.friends.append(object["requestTo"] as! String)
println(self.friends)
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
println(self.friends.count)
yourTableView.reloadData()
}
}

Trying to upload to Parse my votes for each individual image using swift

I am making an app that has a tableview of images and can be upvoted or downvoted by swiping right or left. Im trying to have the votes be logged in to parse on the backend meanwhile i want the votes to appear in each cell. i have added a voteCounter to count the votes but instead of it being for the specific image it shows the same count on every image. How can i stop this and make it that each image has its own vote and how can i save it to the backend of parse?
heres my code so far:
class HomePage: UITableViewController {
var images = [UIImage]()
var titles = [String]()
var imageFile = [PFFile]()
var voteCounter = 0
override func viewDidLoad() {
super.viewDidLoad()
println(PFUser.currentUser())
var query = PFQuery(className:"Post")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) scores.")
for object in objects! {
self.titles.append(object["Title"] as! String)
self.imageFile.append(object["imageFile"] as! PFFile)
self.tableView.reloadData()
}
} else {
// Log details of the failure
println(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 500
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var myCell:cell = self.tableView.dequeueReusableCellWithIdentifier("myCell") as! cell
myCell.rank.text = "21"
myCell.votes.text = "\(voteCounter)"
myCell.postDescription.text = titles[indexPath.row]
imageFile[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.postedImage.image = downloadedImage
}
}
var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
myCell.postedImage.userInteractionEnabled = true;
myCell.postedImage.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Left
myCell.postedImage.userInteractionEnabled = true;
myCell.postedImage.addGestureRecognizer(swipeLeft)
return myCell
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
voteCounter += 1
println("Swiped right")
case UISwipeGestureRecognizerDirection.Left:
voteCounter -= 1
println("Swiped Left")
default:
break
}
}
}
}
Don't use all the different arrays, just keep the array of PFObjects and use them directly. This object should also have the vote count as one of its columns so that when you download you get the count. So you also don't need your vote counter.
You should also look at using PFImageView To display the image. Either that or actually cache the downloaded images yourself.
To update the vote count you should use the increment feature offered by PFObject.
First of all, you work with different pictures, for my part I prefer working with a single table for the tableView.
Every element of your table will correspond to a line of TableView like this :
NOTE : You will have to rearrange the code as you wish
class HomePage: UITableViewController {
var dataTab : [FPObject] : []
override func viewDidLoad() {
super.viewDidLoad()
//Init your data array for tableView
println(PFUser.currentUser())
var query = PFQuery(className:"Post")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) scores.")
for object in objects! {
self.dataTab.append(object)
self.tableView.reloadData()
}
} else {
// Log details of the failure
println(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataTab.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 500
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Get Object at IndexPath.row in dataArray for tableView
let rowObject = self.dataTab[indexPath.row]
let rank = rowObject["rank"]
let votes = rowObject["votes"]
let description = rowObject["Title"]
myCell.rank.text = rank
myCell.votes.text = votes
myCell.postDescription.text = description
//Asynchrone task
rowObject["imageFile"].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
//When download success -- reload tableview to update cells
myCell.postedImage.image = downloadedImage
self.tableView.reloadData()
}
}
return myCell
}
//ACTION WHEN EDIT CELL TABLEVIEW -- Look differents screens
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var upAction = UITableViewRowAction(style: .Default, title: "UP") { (action, indexPath) -> Void in
//Get object at index
let updateObject = self.dataTab[indexPath.row]
//Update data tableview // Increment vote
self.dataTab[indexPath.row]["vote"] = updateObject["vote"] + 1
//UPDATE data in Parse.com
let objectId = updateObject["objectId"]
var query = PFQuery(className:"Post")
query.getObjectInBackgroundWithId(objectId) {
(postObject: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
} else if let postObject = postObject {
postObject["vote"] = postObject["vote"] + 1
postObject.saveInBackground()
}
}
//Reload tableview cells
self.tableView.reloadData()
}
upAction.backgroundColor = UIColor.greenColor()
var downAction = UITableViewRowAction(style: .Default, title: "DOWN") { (action, indexPath) -> Void in
//Get object at index
let updateObject = self.dataTab[indexPath.row]
//Update data tableview // Increment vote
self.dataTab[indexPath.row]["vote"] = updateObject["vote"] - 1
//UPDATE data in Parse.com
let objectId = updateObject["objectId"]
var query = PFQuery(className:"Post")
query.getObjectInBackgroundWithId(objectId) {
(postObject: PFObject?, error: NSError?) -> Void in
if error != nil {
println(error)
} else if let postObject = postObject {
postObject["vote"] = postObject["vote"] - 1
postObject.saveInBackground()
}
}
//Reload tableview cells
self.tableView.reloadData()
}
return [upAction, downAction,]
}
}
screen result to upvote and downvote if you want to use this
I hope I have helped you
Ysée

Resources