0

I'm following along a tutorial and I'd like to expand on on the functionality a bit. I currently have a view controller that allows the user to browse through other users using a Parse query. When the user swipes at a user image I'd like to be able to send the selected user info to a new controller. I know I have to use prepareSegue but I'm not sure how to send that selected user information to a variable in that prepareSeque method.

Here's the view controller. The user I'd like to send to the segue method is labeled "Chosen" below in the wasDragged method:

import UIKit

class SwipeViewController: UIViewController {


    var xFromCenter: CGFloat = 0

    var usernames = [String]()
    var userImages = [NSData]()
    var currentUser = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        println(PFUser.currentUser()["first_name"])

        PFGeoPoint.geoPointForCurrentLocationInBackground { (geopoint: PFGeoPoint!, error: NSError!) -> Void in

            println(error)

            if error == nil {

                println(geopoint)

                var user = PFUser.currentUser()

                user["location"] = geopoint


                var query = PFUser.query()
                query.whereKey("location", nearGeoPoint:geopoint)

                query.limit = 10
                query.findObjectsInBackgroundWithBlock({ (users, error) -> Void in

                    var accepted = [String]()

                    if PFUser.currentUser()["accepted"] != nil {

                       accepted = PFUser.currentUser()["accepted"] as [String]

                    }

                    var rejected = [String]()

                    if PFUser.currentUser()["rejected"] != nil {

                       rejected = PFUser.currentUser()["rejected"] as [String]

                    }

                    for user in users {

                        var gender1 = user["gender"] as? NSString
                        var gender2 = PFUser.currentUser()["interestedIn"] as? NSString

                        if gender1 == gender2 && PFUser.currentUser().username != user.username && !contains(accepted, user.username) && !contains(rejected, user.username) {

                            self.usernames.append(user.username)

                            // Update - chaned as to as!

                            self.userImages.append(user["image"] as NSData)

                        }


                    }

                    var userImage: UIImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
                    println("images:")
                    println(userImage)
                    println(self.userImages)

                    userImage.image = UIImage(data: self.userImages[0])
                    userImage.contentMode = UIViewContentMode.ScaleAspectFit
                    self.view.addSubview(userImage)

                    var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
                    userImage.addGestureRecognizer(gesture)

                    userImage.userInteractionEnabled = true



                })

                user.save()

            }

        }






    }

    func wasDragged(gesture: UIPanGestureRecognizer) {



        let translation = gesture.translationInView(self.view)
        var label = gesture.view!

        xFromCenter += translation.x

        var scale = min(100 / abs(xFromCenter), 1)

        label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)

        gesture.setTranslation(CGPointZero, inView: self.view)

        var rotation:CGAffineTransform = CGAffineTransformMakeRotation(xFromCenter / 200)

        var stretch:CGAffineTransform = CGAffineTransformScale(rotation, scale, scale)

        label.transform = stretch

        if label.center.x < 100 {

            println("Not Chosen")

            PFUser.currentUser().addUniqueObject(self.usernames[self.currentUser], forKey: "rejected")
            PFUser.currentUser().save()

            self.currentUser++

        } else if label.center.x > self.view.bounds.width - 100 {

             //SEND THIS USER TO NEW CONTROLLER
            println("Chosen")

            PFUser.currentUser().addUniqueObject(self.usernames[self.currentUser], forKey: "accepted")
            PFUser.currentUser().save()

            //self.currentUser++

            performSegueWithIdentifier("startGame", sender: nil)

            return

        }

        if gesture.state == UIGestureRecognizerState.Ended {


            label.removeFromSuperview()

            if self.currentUser < self.userImages.count {

                var userImage: UIImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
                userImage.image = UIImage(data: self.userImages[self.currentUser])
                userImage.contentMode = UIViewContentMode.ScaleAspectFit
                self.view.addSubview(userImage)

                var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
                userImage.addGestureRecognizer(gesture)

                userImage.userInteractionEnabled = true

                xFromCenter = 0

            } else {

                println("No more users")

            }

        }
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        //var user = ?? I want to send this user info to the segue to GameViewController

        let destinationVC = segue.destinationViewController as GameViewController
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}

Any help would be greatly appreciated. Thanks!

2 Answers 2

1

You should have a user variable in your GameViewController class and in your prepareForSegue function set it to the user that was swiped.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "startGame") {
        let destinationVC = segue.destinationViewController as GameViewController
        destinationVC.user = self.currentUser; //or whatever variables you want to set
    }
}

I have included code to check if the segue is a "startGame" segue in case you wanted to have other segues which do not pass a user.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I think this is what I was looking for. I set the user to destinationVC.user = PFUser.currentUser().addUniqueObject(self.usernames[self.currentUser], forKey: "accepted") but I get an error on the line: "Void" is not convertible to PFUser. I'm trying to get that specific user from the wasDragged method. What does this error mean? Thanks!
You are setting the user to the result of the "addUniqueObject()" method, which returns void. You need to set the user variable to the method which returns the user, which I am assuming is "PFUser.currentUser()".
I think I'm getting it! So, the segue does work but I'm still not sure exactly how to call the destinationVC.user variable set in SwipeViewController. So, let's say I want to set a label.text in GameViewController to equal the user's name. Will GameViewController have access to destinationVC.user?
destinationVC IS the GameViewController that you are segueing too. In your prepareForSegue method you are just accessing it before it is presented. The reason you access it before hand is so you can set some of its variable (for example its user variable or any other variable the GameViewCont has). If you want to set a labels text from your current ViewController then you want to create a string variable in GameViewController called "name" or something and in your prepareForSegue method set destinationVC.name = "Text" and in your GameViewController viewDidLoad set the uilabel to that string.
You do this because you dont want to access the UI directly in prepareForSegue because it hasnt been presented yet. Sorry im on mobile btw.
|
0

Instead of passing nil for the sender argument in performSegueWithIdentifier:sender: you can pass "Chosen". You can pass any object you want in that parameter. It will then be the sender argument in prepareForeSegue:sender:

2 Comments

Thanks for the quick reply! Would I need to include additional variables in the prepareForSegue or will it get it from the Chosen sender? I'll be able to test this as soon as I fix another issue I just found in the app
@james, Sorry, I think I misread your code. You want to pass on the current user, correct? Then you should pass self.currentUser.

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.