0

I'm trying to pass the data from a TableView so when a cell is pressed, the data on that cell will be transferred to a viewController and display it there, but I cannot seem to get it to work. I tried these posts:

swift segue not passing data from tableview

Passing data from tableView to ViewController in Swift

Pass data through unwind segue

But either I get an error that crashes the app, or it doesn't display anything. What I'm trying to do is get a user to comment on a post that another user posted, so I'm trying to get the info from the post to display it in detail, but that's where I'm having trouble. This is the function I'm using to pass the data from the table view:

func objectAtIndexPath(indexPath: NSIndexPath) -> PFObject {
    return self.timelineData[indexPath.row] as! PFObject
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if(segue.identifier == "lookPosts"){
        let VC = segue.destinationViewController as! DetailViewContoller
        let indexPath: NSIndexPath! = self.tableView.indexPathForSelectedRow()
        VC.post = self.objectAtIndexPath(indexPath!) as PFObject
    }
}

and this is the class of the DetailViewController:

import UIKit
import Parse

class DetailViewContoller: UIViewController, UITableViewDelegate, UITextViewDelegate {

    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var postTextView: UITextView!
    @IBOutlet weak var commentTableView: UITableView!

    var post: PFObject?
    var commentView: UITextView?
    var footerView: UIView?
    var contentHeight: CGFloat = 0

    var comments: [String]?
    let FOOTERHEIGHT : CGFloat = 50;

    override func viewDidLoad() {
        super.viewDidLoad()

        commentTableView.delegate = self

        /* Setup the keyboard notifications */
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

        //gets the current user username
        usernameLabel.text = PFUser.currentUser()!.username as String?

        if(post?.objectForKey("comments") != nil) {
            comments = post?.objectForKey("comments") as? [String]
        }

        println(post)
        println(post?.objectForKey("content"))
        //self.postTextView.text = post?.objectForKey("content") as? String
    }

    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)

        self.postTextView.text = post?.objectForKey("content") as? String
        println(postTextView.text)
    }


    func keyBoardWillShow(notification: NSNotification) {
        var info:NSDictionary = notification.userInfo!
        var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

        var keyboardHeight:CGFloat =  keyboardSize.height - 40


        var animationDuration:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

        var contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
        self.commentTableView.contentInset = contentInsets
        self.commentTableView.scrollIndicatorInsets = contentInsets

    }

    func keyBoardWillHide(notification: NSNotification) {

        self.commentTableView.contentInset = UIEdgeInsetsZero
        self.commentTableView.scrollIndicatorInsets = UIEdgeInsetsZero
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let count = comments?.count {
            return count
        }
        return 0
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = commentTableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentTableViewCell
        cell.commentLabel?.text = comments![indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.footerView != nil {
            return self.footerView!.bounds.height
        }
        return FOOTERHEIGHT
    }

    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        footerView = UIView(frame: CGRect(x: 0, y: 0, width: commentTableView.bounds.width, height: FOOTERHEIGHT))
        footerView?.backgroundColor = UIColor(red: 243.0/255, green: 243.0/255, blue: 243.0/255, alpha: 1)
        commentView = UITextView(frame: CGRect(x: 10, y: 5, width: commentTableView.bounds.width - 80 , height: 40))
        commentView?.backgroundColor = UIColor.whiteColor()
        commentView?.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)
        commentView?.layer.cornerRadius = 2
        commentView?.scrollsToTop = false

        footerView?.addSubview(commentView!)
        let button = UIButton(frame: CGRect(x: commentTableView.bounds.width - 65, y: 10, width: 60 , height: 30))
        button.setTitle("Reply", forState: UIControlState.Normal)
        button.backgroundColor = UIColor(red:  0/0.0, green: 179/255.0, blue: 204/255.0, alpha: 100.0/100.0)
        button.layer.cornerRadius = 5
        button.addTarget(self, action: "reply", forControlEvents: UIControlEvents.TouchUpInside)
        footerView?.addSubview(button)
        commentView?.delegate = self
        return footerView
    }


    //Hide keyboard after touching background
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    //remaining characters
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{

        if (text == "\n") {
            textView.resignFirstResponder()
        }

        return true
    }

    func reply() {
        post?.addObject(commentView!.text, forKey: "comments")
        post?.saveInBackground()
        if let tmpText = commentView?.text {
            comments?.append(tmpText)
        }
        commentView?.text = ""
        println(comments?.count)
        self.commentView?.resignFirstResponder()
        self.commentTableView.reloadData()
    }
}

So my question here is: Is there another way of passing the data? or what am I doing wrong that the data is not passing?

13
  • Have you checked the name of your segue and made sure the block of code inside the if clause in prepareForSegue is running? Commented Sep 2, 2015 at 4:47
  • @vigneshv the way I have it let VC = segue.destinationViewController as! DetailViewContoller makes the app crash, I have to change it to: if let destinationVC = segue.destinationViewController as? DetailViewContoller {} but once I change it to that, it doesn't display the data Commented Sep 2, 2015 at 4:52
  • well it shouldn't crash the app. It means that the casting failed, so no data is sent. Make sure you're not pushing a navigation controller in this segue, this should be fairly easy to debug. Commented Sep 2, 2015 at 4:57
  • Like FruitAddict said, this is probably due to the fact that your destinationViewController is not a DetailViewController, in addition to FruitAddict suggested, make sure your ViewController in storyboard is a subclass of DetailViewController. Commented Sep 2, 2015 at 4:59
  • 1
    That's not the point. Make sure that the lookPosts segue poiints to the DetailsViewController, not something like it's wrapping navigation controller. Also make sure that this view has its class set correctly in the storyboard. Commented Sep 2, 2015 at 5:05

1 Answer 1

0

Here is one way to acheive that:

If your data is not large then you can use NSUserDefaults for that.

First store your data to memory:

NSUserDefaults.standardUserDefaults().setObject(yourObject, forKey: "yourKey")

Read your data from memory in another viewController:

let yourObject = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as! PFObject

Hope it helps.

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

7 Comments

I don't belive it's large since I just want to pass the data of the cell the user is clicking, so I guess this would work, but where do I apply this? Inside the prepareForSegue function?
You can store your object in didSelectRowAtIndexPath.
This will store it app-wide FYI, and you could store the data in the prepareForSegue. Its also persistent, so even if the user quits the app, the data will still be stored.
@DharmeshKheni using it this way I wouldn't need to perform the segue function right?
Could I save it at cellForRowAtIndexPath?
|

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.