用Parse查询和更新投票?

时间:2015-05-28 09:10:55

标签: ios swift parse-platform

我正在尝试建立一个投票系统Parse作为我的后端。

我想使用向左和向右滑动作为投票方法,我使用query.getObjectInBackgroundWithID,以便我可以将投票计数更新到我的后端。

我在查询它时遇到了麻烦,并且还保留了后面的投票并将其附加到单元格中,以便在tableview单元格上添加投票计数。

在我的查询日志中继续收到此错误:

  

没有与查询匹配的结果(代码:101,版本:1.7.2)

我该如何纠正?另外,在我让查询工作并更新后端后,如何使投票系统工作?

到目前为止,这是我的代码:

import UIKit
import Parse


class HomePage: UITableViewController {

    let post = PFObject(className: "Post")
    var images = [UIImage]()
    var titles = [String]()
    var imageFile = [PFFile]()
     var voteCounter = 0

    var count = [Int]()



    override func viewDidLoad() {
        super.viewDidLoad()

        println(PFUser.currentUser())

        var query = PFQuery(className:"Post")
        query.orderByDescending("createdAt")
        query.limit = 15
        query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil  {
                println("Successfully retrieved \(objects!.count) scores.")
                println(objects!)
                if let objects = objects as? [PFObject] {
                for object in objects {

                        if let title = object["Title"] as? String {
                            self.titles.append(title)
                        }
                        if let imgFile = object["imageFile"] as? PFFile {
                            self.imageFile.append(imgFile)
                        }
                        if let voteCounter = object["count"] as? Int {
                        self.count.append(voteCounter)
                        }
                        self.tableView.reloadData()

                }
            } else {
                // Log details of the failure
                println(error)
            }
        }

    }
            }




                /* 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()

                }*/



    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 = "\(count)"
        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)

这是我收到错误的查询:

        var query = PFQuery(className:"Post")
    query.getObjectInBackgroundWithId("count") {
    (Post: PFObject?, error: NSError?) -> Void in
    if error != nil {
    println(error)
    } else if let Post = Post {
    Post["count"] = self.voteCounter
    Post.saveInBackground()
    }
    }

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

    }

这也是我的Parse后端:

Parse

我现在添加了新代码

     import UIKit
import Parse


class HomePage: UITableViewController {

    let post = PFObject(className: "Post")
    var images = [UIImage]()
    var titles = [String]()
    var imageFile = [PFFile]()
    var votingObjects: [PFObject] = []

 override func viewDidLoad() {
        super.viewDidLoad()

        println(PFUser.currentUser())

        println(PFUser.currentUser())

        var query = PFQuery(className:"Post")
        query.orderByDescending("createdAt")
        query.limit = 15
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil  {
                println("Successfully retrieved \(objects!.count) scores.")
                println(objects!)
                for objectRaw in objects! {
                    let object = objectRaw as! PFObject

                    self.votingObjects.append(object)
                    // Adding them to the array
                    if let title = object["Title"] as? String {
                        self.titles.append(title)
                    }
                    if let imgFile = object["imageFile"] as? PFFile {
                        self.imageFile.append(imgFile)
                    }


                }
                dispatch_async(dispatch_get_main_queue(), {
                    self.tableView.reloadData() 
// Updating the tableView on the main thread - important. Do some research on Grand Central Dispatch :)
                })
            } else {
                println(error)
                // 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的正确代码是什么=

        myCell.votes.text = votingObjects[indexPath.row]["count"] as? String
        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:
                updateVote(true, objectId: String())
                println("Swiped right")
                case UISwipeGestureRecognizerDirection.Left:
                updateVote(false, objectId: String())
                println("Swiped Left")
                default:
                    break
                }
            }
        }

    func updateVote(increment: Bool, objectId : String) {

        // Create a pointer to an object of class Posts with id 'objectId'
        var object = PFObject(withoutDataWithClassName: "Post", objectId: objectId)

        // Increment the current value of the quantity key by 1
        if increment == true {
            object.incrementKey("count", byAmount: 1)
        } else {
            object.incrementKey("count", byAmount: -1)
        }

        // Save
        object.saveInBackgroundWithBlock(nil)
    }
}

但是每当我滑动并启动手势识别器时,我都会一直收到无法更新的错误,而无需特定的objectId。我也无法弄清楚如何在我的单元格中显示投票

1 个答案:

答案 0 :(得分:1)

看起来您正在查询Parse数据库以查找不存在的objectID。这是因为当您收到对象时,属性" count"是正确的投票数...但是当你查询一个对象时,你正在使用" count"作为显然不会起作用的objectID。您使用变量计数的想法也不起作用。

我建议您稍微调整一下结构。

从初始查询接收对象时,将它们存储在Parse Objects数组中。这样,您可以保留所有信息,更新它们会更容易。还将提供一个属性object.objectId,它是一个String,这是再次查询db时所需要的。

另一个提示是Parse在处理类型number

的列时支持递增函数

此外,在处理后台线程时,您应该使用GCD在主线程上进行任何UI调用。

代码:

初始查询 -

var votingObjects: [PFObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        println(PFUser.currentUser())

        var query = PFQuery(className:"Post")
        query.orderByDescending("createdAt")
        query.limit = 15
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]!, error: NSError!) -> Void in
            if error == nil  {
                println("Successfully retrieved \(objects!.count) scores.")
                println(objects!)
                for objectRaw in objects {
                    let object = objectRaw as! PFObject
                    self.votingObjects.append(object) // Adding them to the array
                }
                dispatch_async(dispatch_get_main_queue(), {
                    self.tableView.reloadData() // Updating the tableView on the main thread - important. Do some research on Grand Central Dispatch :)
                })
            } else {
                // Error
            }
        }
    }
    // Pass true if you want to upvote or false if downvote
    func updateVote(increment: Bool, objectId : String) {
        // Create a pointer to an object of class Posts with id 'objectId'
        var object = PFObject(withoutDataWithClassName: "Posts", objectId: objectId)

        // Increment the current value of the quantity key by 1
        if increment == true {
            object.incrementKey("count", byAmount: 1)
        } else {
            object.incrementKey("count", byAmount: -1)
        }

        // Save
        object.saveInBackgroundWithBlock(nil)
    }
}

你的tableView函数现在都将链接到数组..

numberOfRows只会使用votingObjects.count TitleForRow将使用votingObject[indexPath.row]["Title"]! // Should be 'title'

每当您想要引用投票对象ID时,只需使用votingObject[index].objectId

即可

希望我没有错过任何事情:)