1

I am trying to pass data in a UITextField that the user will input to go into a cell in a Collection View in another View Controller.

I want to create new 'posts' to be added to my feed every single time someone presses the 'upload' button, so the Collection View cell needs to somehow upload the given information and then clear the cell.

I don't know how to approach passing the data to the Collection View.

Here is my View Controller and my Cell code.

import UIKit
import Firebase

class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


    @IBOutlet weak var previewImage: UIImageView!
    @IBOutlet weak var postBtn: UIButton!
    @IBOutlet weak var selectBtn: UIButton!

    @IBOutlet weak var thisTextField: UITextField!


    @IBOutlet weak var thatTextField: UITextField!
    var picker = UIImagePickerController()



    @IBAction func thisPhotoUpload(_ sender: Any) {

        if thisTextField.text != "" || thatTextField.text != ""
        {
            performSegue(withIdentifier: "segue", sender: self)
        }

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        var postCell = segue.destination as! PostCell

        postCell.thisString = thisTextField.text!

        postCell.thatString = thatTextField.text!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        picker.delegate = self
    }


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            self.previewImage.image = image
            selectBtn.isHidden = true
            postBtn.isHidden = false
        }

        self.dismiss(animated: true, completion: nil)
    }


    @IBAction func selectPressed(_ sender: Any) {

        picker.allowsEditing = true
        picker.sourceType = .photoLibrary

        self.present(picker, animated: true, completion: nil)

    }


    @IBAction func postPressed(_ sender: Any) {
        AppDelegate.instance().showActivityIndicator()

        let uid = FIRAuth.auth()!.currentUser!.uid
        let ref = FIRDatabase.database().reference()
        let storage = FIRStorage.storage().reference(forURL: "gs://instagram-f3f20.appspot.com")

        let key = ref.child("posts").childByAutoId().key
        let imageRef = storage.child("posts").child(uid).child("\(key).jpg")

        let data = UIImageJPEGRepresentation(self.previewImage.image!, 0.6)

        let uploadTask = imageRef.put(data!, metadata: nil) { (metadata, error) in
            if error != nil {
                print(error!.localizedDescription)
                AppDelegate.instance().dismissActivityIndicatos()
                return
            }

            imageRef.downloadURL(completion: { (url, error) in
                if let url = url {
                    let feed = ["userID" : uid,
                                "pathToImage" : url.absoluteString,
                                "likes" : 0,
                                "author" : FIRAuth.auth()!.currentUser!.displayName!,
                                "postID" : key] as [String : Any]

                    let postFeed = ["\(key)" : feed]

                    ref.child("posts").updateChildValues(postFeed)
                    AppDelegate.instance().dismissActivityIndicatos()

                    self.dismiss(animated: true, completion: nil)
                }
            })

        }

        uploadTask.resume()

    }

}

CollectionViewCell subclass

import UIKit
import Firebase

class PostCell: UICollectionViewCell {

    @IBOutlet weak var postImage: UIImageView!
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var likeLabel: UILabel!


    @IBOutlet weak var likeBtn: UIButton!
    @IBOutlet weak var unlikeBtn: UIButton!


    @IBOutlet weak var thisLabel: UILabel!
    @IBOutlet weak var thisButton: UIButton!
    @IBOutlet weak var thatLabel: UILabel!
    @IBOutlet weak var thatButton: UIButton!

    var postID: String!
    var thisString = String()
    var thatString = String()



    override func awakeFromNib() {
        super.awakeFromNib()




        thisLabel.text = thisString

        thisButton.setTitle(thisString, for: UIControlState.normal)

        thatLabel.text = thisString

        thatButton.setTitle(thisString, for: UIControlState.normal)
    }

    @IBAction func likePressed(_ sender: Any) {
        self.likeBtn.isEnabled = false
        let ref = FIRDatabase.database().reference()
        let keyToPost = ref.child("posts").childByAutoId().key

        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

            if let post = snapshot.value as? [String : AnyObject] {
                let updateLikes: [String : Any] = ["peopleWhoLike/\(keyToPost)" : FIRAuth.auth()!.currentUser!.uid]
                ref.child("posts").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in

                    if error == nil {
                        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                            if let properties = snap.value as? [String : AnyObject] {
                                if let likes = properties["peopleWhoLike"] as? [String : AnyObject] {
                                    let count = likes.count
                                    self.likeLabel.text = "\(count) Likes"

                                    let update = ["likes" : count]
                                    ref.child("posts").child(self.postID).updateChildValues(update)

                                    self.likeBtn.isHidden = true
                                    self.unlikeBtn.isHidden = false
                                    self.likeBtn.isEnabled = true
                                }
                            }
                        })
                    }
                })
            }


        })

        ref.removeAllObservers()
    }


    @IBAction func unlikePressed(_ sender: Any) {
        self.unlikeBtn.isEnabled = false
        let ref = FIRDatabase.database().reference()


        ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

            if let properties = snapshot.value as? [String : AnyObject] {
                if let peopleWhoLike = properties["peopleWhoLike"] as? [String : AnyObject] {
                    for (id,person) in peopleWhoLike {
                        if person as? String == FIRAuth.auth()!.currentUser!.uid {
                            ref.child("posts").child(self.postID).child("peopleWhoLike").child(id).removeValue(completionBlock: { (error, reff) in
                                if error == nil {
                                    ref.child("posts").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                                        if let prop = snap.value as? [String : AnyObject] {
                                            if let likes = prop["peopleWhoLike"] as? [String : AnyObject] {
                                                let count = likes.count
                                                self.likeLabel.text = "\(count) Likes"
                                                ref.child("posts").child(self.postID).updateChildValues(["likes" : count])
                                            }else {
                                                self.likeLabel.text = "0 Likes"
                                                ref.child("posts").child(self.postID).updateChildValues(["likes" : 0])
                                            }
                                        }
                                    })
                                }
                            })

                            self.likeBtn.isHidden = false
                            self.unlikeBtn.isHidden = true
                            self.unlikeBtn.isEnabled = true
                            break

                        }
                    }
                }
            }

        })
        ref.removeAllObservers()
    }
}

Right now I'm getting the error in my View Controller on the 'var postCell = segue.destination as! PostCell' line. The error says 'Bad Execution'

Any and all help would be great.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
priM
  • 37
  • 1
  • 1
  • 6

1 Answers1

1

Segue.destination returns a UIViewController not a UICollectionViewCell

You should create a variable in the next viewcontroller and assign to it the text then show it there.

let vc = segue.destination as! NextViewController
vc.thisText = thisTextField.text!
vc.thatText = thatTextField.text!

And then in the NextViewController you will have the inputs in thisText and thatText

Farid Al Haddad
  • 833
  • 9
  • 19