I am using this code to create a feed view that shows users, images, and comments similar to instagram. For some reason, the cells on the feed are duplicating the current user's posts. Not only that, but it is also putting the incorrect username with the images on the duplicate cells. What am I doing wrong?
import UIKit
import Parse
class FeedTableViewController: UITableViewController {
var usersBeingFollowed = [String]()
var imageFiles = [PFFile]()
var imageComment = [""]
var usernames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
let getFollowedUsersQuery = PFQuery(className: "Followers")
getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
self.usernames.removeAll(keepCapacity: true)
self.imageComment.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
self.usersBeingFollowed.removeAll(keepCapacity: true)
if let objects = objects {
for object in objects {
let followedUser = object["following"] as! String
let getFollowedUsers = PFQuery(className: "Post")
getFollowedUsers.whereKey("userId", equalTo: followedUser)
let getCurrentUser = PFQuery(className: "Post")
getCurrentUser.whereKey("userId", equalTo: (PFUser.currentUser()?.objectId)!)
var query = PFQuery.orQueryWithSubqueries([getFollowedUsers,getCurrentUser])
query.findObjectsInBackgroundWithBlock({ (imageObjects, error) -> Void in
if let objects = imageObjects {
for images in objects {
let userQuery = PFUser.query()
userQuery?.whereKey("_id", equalTo: images["userId"])
userQuery?.findObjectsInBackgroundWithBlock({ (user, error) -> Void in
print(user)
if let user = user {
for username in user {
self.usernames.append(username["username"] as! String)
}
}
})
self.imageFiles.append(images["imageFile"] as! PFFile)
self.imageComment.append(images["imageComment"] as! String)
self.tableView.reloadData()
}
}
})
}
}
}
}
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 usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("imagePostCell", forIndexPath: indexPath) as! cell
if imageFiles.count > 0{
myCell.userLabel.text = "\(usernames[indexPath.row]) completed the \(imageComment[indexPath.row]) challenge!"
imageFiles[indexPath.row].getDataInBackgroundWithBlock({ (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.imagePost.image = downloadedImage
// self.tableView.reloadData()
}
})
}
return myCell
}
You should reset the cell property before add new values, you can use
prepareForReuse()
More info on Apple Doc https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITableViewCell_Class/index.html#//apple_ref/occ/instm/UITableViewCell/prepareForReuse
It will be obviously, generate the duplicate content because you have put the condition that if imageFiles.count > 0 then the data will be displayed.
But what when there are no images? It will definitely take the value from reusable UITableViewCell. Check the below change:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("imagePostCell", forIndexPath: indexPath) as! cell
if imageFiles.count > 0{
myCell.userLabel.text = "\(usernames[indexPath.row]) completed the \(imageComment[indexPath.row]) challenge!"
imageFiles[indexPath.row].getDataInBackgroundWithBlock({ (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.imagePost.image = downloadedImage
// self.tableView.reloadData()
}
})
}else{
myCell.userLabel.text = "Put What You Want Here" //make just nil
myCell.imagePost.image = UIImage(name: "placeholder.png") //Some Placeholder image when there is no data
}
return myCell
}
Related
I have seen the following questions.
Get data from a pointer's row in Parse (ios)
and various other questions but still unable to figure out.
I have a class in Parse called 'Plumber'
As you can see the 'practiceArea' is a pointer to this class called 'PracticeArea' (mind the uppercase P in the class)
So from here I want to extract the corresponding 'title' column value for the corresponding pointer. How can I do this?
This is my code so far
//
// Directory.swift
// plumber_main
//
// Created by James on 13/4/16.
// Copyright © 2016 James. All rights reserved.
//
import UIKit
import Parse
class Directory: UITableViewController {
#IBOutlet var plumbersDirectory: UITableView!
var profImages = [PFFile]()
var plumberName = [String]()
var plumberRate = [NSNumber]()
var plumberPracArea = [PFObject]()
var plumberExp = [String]()
var refresher: UIRefreshControl!
func refresh()
{
let query_one = PFQuery(className: "PracticeArea")
query_one.includeKey("title")
let query = PFQuery(className: "plumber")
query.includeKey("practiceArea")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock(
{
(listll: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(listll!.count) names of the plumbers.")
// Do something with the found objects
if let objects = listll {
for object in objects {
print(object)
self.profImages.append(object["photo"] as! PFFile)
self.plumberName.append(object["name"] as! String)
self.plumberExp.append(object["expLevel"] as! String)
self.plumberPracArea.append(object["practiceArea"] as! PFObject)
print(object ["practiceArea"].objectId)
self.plumberRate.append(object["ratePerHr"] as! NSNumber)
// print(object["plumber_Name"] as! String )
// self.plumbersname.append(object["plumber_Name"] as! String)
//self.lblName.text = object["plumber_Name"] as? String
}
self.plumbersDirectory.reloadData()
}
print(self.plumberName.count)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
self.tableView.reloadData()
self.refresher.endRefreshing()
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refrehsh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
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 plumberName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let plumbercell: plumber_Directory_Cell = tableView.dequeueReusableCellWithIdentifier("plumberlistproto") as! plumber_Directory_Cell
plumbercell.name.text = plumberName[indexPath.row]
plumbercell.exp.text = plumberExp[indexPath.row]
plumbercell.pracArea.text = String(plumberPracArea[indexPath.row])
plumbercell.price.text = String (plumberRate[indexPath.row])
profImages[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if imageData != nil {
let image = UIImage(data: imageData!)
plumbercell.mini_image.image = image
}
else
{
print(error)
} }
//cell.textLabel?.text = plumbersname[indexPath.row]
return plumbercell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
}
}
Try this
func refresh()
{
let query = PFQuery(className: "PracticeArea")
query.includeKey("practiceArea")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock( {
(listll: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(listll!.count) names of the plumbers.")
// Do something with the found objects
if let objects = listll {
self.plumberName = objects
} else {
self.plumberName.removeAllObjects()
}
self.plumbersDirectory.reloadData()
print(self.plumberName.count)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let plumbercell: plumber_Directory_Cell = tableView.dequeueReusableCellWithIdentifier("plumberlistproto") as! plumber_Directory_Cell
let object = plumberName[indexPath.row]
plumbercell.name.text = object["name"]
plumbercell.exp.text = object["expLevel"]
let practiceArea = object["practiceArea"]
plumbercell.pracArea.text = practiceArea["title"]
plumbercell.pracArea.text = String(plumberPracArea[indexPath.row])
plumbercell.price.text = String (plumberRate[indexPath.row])
profImages[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if imageData != nil {
let image = UIImage(data: imageData!)
plumbercell.mini_image.image = image
}
else
{
print(error)
} }
//cell.textLabel?.text = plumbersname[indexPath.row]
return plumbercell
}
You were really close and definitely not "doing it all wrong". Since you've already included the key in the query request, when you want the information from that object too, then you just need this
let practiceArea = object["projectArea"] as! PFObject
let title = practiceArea["title"] as? String
you should query the different class if you want to use the pointer with the "includeKey"...
let query: PFQuery = PFQuery(className: "PracticeArea")
query.orderByDescending("createdAt")
query.includeKey("practiceArea")
query.findObjectsInBackgroundWithBlock{
(objects:[PFObject]?, error:NSError?)->Void in
if error == nil{
for object in objects! {
//do stuff with each object
}
}
}
There is a SS of error
This happened after add refresh method in to viewDidLoad for pull to refresh . Im using parse.com and that followers table is empty.
I found some questions about some error. But i didn't found anything same as my question or maybe i don't understand.
How can i fix this what is the problem ?
import UIKit
import Parse
class TableViewController: UITableViewController {
var usernames = [""]
var userids = [""]
var isFollowing = ["":false]
var refresher: UIRefreshControl!
func refresh() {
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.usernames.removeAll(keepCapacity: true)
self.userids.removeAll(keepCapacity: true)
self.isFollowing.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
if user.objectId! != PFUser.currentUser()?.objectId {
self.usernames.append(user.username!)
self.userids.append(user.objectId!)
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: (PFUser.currentUser()?.objectId)!)
query.whereKey("following", equalTo: user.objectId!)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
if objects.count > 0 {
self.isFollowing[user.objectId!] = true
} else {
self.isFollowing[user.objectId!] = false
}
}
if self.isFollowing.count == self.usernames.count {
self.tableView.reloadData()
self.refresher.endRefreshing()
}
})
}
}
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresher")
refresher.addTarget(self , action: "refresh" , forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
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 usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = usernames[indexPath.row]
let followedOnjectId = userids[indexPath.row]
if isFollowing[followedOnjectId] == true {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
let followedOnjectId = userids[indexPath.row]
if isFollowing[followedOnjectId] == false{
isFollowing[followedOnjectId] = true
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
var following = PFObject(className: "followers")
following["following"] = userids[indexPath.row]
following["follower"] = PFUser.currentUser()?.objectId
following.saveInBackground()
}else
{
isFollowing[followedOnjectId] = false
cell.accessoryType = UITableViewCellAccessoryType.None
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: userids[indexPath.row])
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for objects in objects {
objects.deleteInBackground()
}
}
})
}
}
}
(PFUser.currentUser()?.objectId)!
or the query-var is nil. That causes the exception.
You should probably use the if let construct
if let objectId = PFUser.currentUser()?.objectId {
query.whereKey("follower", equalTo: objectId)
}
or if the code should be just executed when all the values exist you can use the guard keyword.
guard let a = optionalType?.variable?.a, b = optionalType?.variable?.b else { return }
I am creating a view that shows a list of users. The current user is able to click on one of the cells, thus following or unfollowing the user in that cell. For some reason, checkmarks are showing up in cells that should not have the checkmark(meaning the current user is following someone that he really isn't). The images for the users are also incorrect. I imagine the reason for that is related to the checkmark error. What am I doin wrong? PLEASE HELP!
import UIKit
import Parse
class TableViewController: UITableViewController {
var refresher: UIRefreshControl!
var usernames = [""]
var userIds = [""]
var userPics = [String:PFFile]()
var isFollowing = ["":false]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
}
func refresh (){
let query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (object, error) -> Void in
if let users = object {
self.usernames.removeAll(keepCapacity: true)
self.userIds.removeAll(keepCapacity: true)
self.isFollowing.removeAll(keepCapacity: true)
self.userPics.removeAll(keepCapacity: true)
for objects in users {
if let user = objects as? PFUser {
if user.objectId != PFUser.currentUser()?.objectId {
self.usernames.append(user.username!)
self.userIds.append(user.objectId!)
if let image = user["profileImage"] {
self.userPics[user.objectId!] = image as? PFFile
}
let query = PFQuery(className: "Followers")
query.whereKey("following", equalTo: user.objectId!)
query.whereKey("follower", equalTo: (PFUser.currentUser()!.objectId)!)
query.findObjectsInBackgroundWithBlock({ (object, error) -> Void in
if let object = object {
if object.count > 0 {
self.isFollowing[user.objectId!] = true
} else {
self.isFollowing[user.objectId!] = false
}
}
if self.isFollowing.count == self.usernames.count {
print(self.isFollowing)
print(self.userIds)
self.tableView.reloadData()
self.refresher.endRefreshing()
}
})
}
}
}
}
})
}
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 usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UsersTableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UsersTableViewCell
cell.userLabel.text = usernames[indexPath.row]
if isFollowing[userIds[indexPath.row]] == true {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
cell.userImage.frame = CGRectMake(0, 0, 100, 100)
cell.userImage.clipsToBounds = true
cell.userImage.layer.cornerRadius = cell.userImage.frame.height/2
if userPics[userIds[indexPath.row]] != nil {
userPics[userIds[indexPath.row]]!.getDataInBackgroundWithBlock { (data, error) -> Void in
if let data = data {
cell.userImage.image = UIImage(data: data)
}
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell: UsersTableViewCell = tableView.cellForRowAtIndexPath(indexPath)! as! UsersTableViewCell
if isFollowing[userIds[indexPath.row]] == false {
isFollowing[userIds[indexPath.row]] = true
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
let following = PFObject(className: "Followers")
following["following"] = userIds[indexPath.row]
following["follower"] = PFUser.currentUser()?.objectId
following.saveInBackground()
} else {
isFollowing[userIds[indexPath.row]] = false
cell.accessoryType = UITableViewCellAccessoryType.None
let query = PFQuery(className: "Followers")
query.whereKey("following", equalTo: userIds[indexPath.row])
query.whereKey("follower", equalTo: (PFUser.currentUser()?.objectId)!)
query.findObjectsInBackgroundWithBlock({ (object, error) -> Void in
if let object = object {
for users in object {
users.deleteInBackground()
}
}
})
}
}
}
Like Michael said, you need to clear the checkmark, try with this code instead of your if
cell.accessoryType = isFollowing[userIds[indexPath.row]] ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
I'm building out a image feed that includes an image followed by a username label inside of a table view. For some reason, the cell images don't match the correct usernames. It almost seems that the images are downloaded in a different order than the usernames, but that can't be the case. Please help!
EDIT: After doing some console logging, I see that the images are downloaded and appended to the images array, in an different order than the usernames. BUT I don't know why, nor how to fix it.
import UIKit
class TrendingChallengeTableViewCell: UITableViewCell {
#IBOutlet var postImage: UIImageView!
#IBOutlet var postComment: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
self.postImage.image = nil
self.postComment.text = ""
}
}
import UIKit
import Parse
var pressedChallenge: String?
class TrendingChallengeTableViewController: UITableViewController {
var images = [PFFile]()
var usernames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
let query = PFQuery(className: "Post")
query.whereKey("imageComment", equalTo: pressedChallenge!)
query.findObjectsInBackgroundWithBlock { (object, error) -> Void in
self.usernames.removeAll(keepCapacity: true)
self.images.removeAll(keepCapacity: true)
if let object = object {
for images in object {
self.images.append(images["imageFile"] as! PFFile)
let userQuery = PFUser.query()
userQuery?.whereKey("_id", equalTo: images["userId"])
userQuery?.findObjectsInBackgroundWithBlock({ (object, error) -> Void in
if let object = object {
for user in object {
self.usernames.append(user["username"] as! String)
self.tableView.reloadData()
}
}
})
}
}
}
}
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 usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let trendCell = tableView.dequeueReusableCellWithIdentifier("trendingCell", forIndexPath: indexPath) as! TrendingChallengeTableViewCell
trendCell.postComment.text = "\(usernames[indexPath.row]) completed the \(pressedChallenge!) challenge!"
images[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
trendCell.postImage.image = downloadedImage
}
}
return trendCell
}
}
Try telling both your queries to sort in a specific way before fetching the objects, ie:
let query = PFQuery(className: "Post")
query.whereKey("imageComment", equalTo: pressedChallenge!)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (object, error) -> Void in
//etc
}
Do this for the second query as well.
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