vc1:
protocol UpdateVC1 {
func updateButtons(likeIt: Bool)
}
import UIKit
import Firebase
class NewsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,
commentButtonDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var posts = [Post]()
var AFan = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fetchPosts()
self.view.setNeedsLayout()
self.loadView()
}
var delegate: UpdateVC1?
func fetchPosts(){
let ref = Database.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
let users = snapshot.value as! [String : AnyObject]
for (_,value) in users {
if let uid = value["uid"] as? String{
let userImage = value["urlToImage"] as? String
if uid == Auth.auth().currentUser?.uid{
if let AFanOf = value["a fan"] as? [String : String]{
for(_,user) in AFanOf{
self.AFan.append(user)
}
}
self.AFan.append(Auth.auth().currentUser!.uid)
ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: {(snap) in
for postSnapshot in snap.children.allObjects as! [DataSnapshot] {
let value = postSnapshot.value as! [String : AnyObject]
if let userID = value["userID"] as? String{
for each in self.AFan{
if each == userID{
let posst = Post()
if let author = value["author"] as? String,
let likes = value["likes"] as? Int,
let pathToImage = value["pathToImage"] as? String,
let postID = value["postID"] as? String{
posst.author = author
posst.likes = likes
posst.pathToImage = pathToImage
posst.postID = postID
posst.authorImage = userImage
if let people = value["peopleWhoLike"] as? [String : AnyObject]{
for (_,person) in people{
posst.peopleWhoLike.append(person as! String)
}
}
if let pastDate = value["createdAt"] as? String{
posst.timeAgo = pastDate
}
self.posts.append(posst)
}
}
}
self.collectionView.reloadData()
}
}
})
}
}
}
})
ref.removeAllObservers()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath)
as! PostCell
let inverseIndex = self.posts.count - indexPath.row - 1
cell.postImage.downloadImage(from: self.posts[inverseIndex].pathToImage)
cell.authorLabel.text = self.posts[inverseIndex].author
cell.likeLabel.text = "\(self.posts[inverseIndex].likes!) Likes"
cell.postID = self.posts[inverseIndex].postID
cell.authorImage.downloadImage(from: self.posts[inverseIndex].authorImage)
let string = self.posts[inverseIndex].timeAgo
let df = DateFormatter()
df.dateFormat = "yyyy/MM/dd, H:mm:ss"
let result = df.date(from: string!)
let timeDate = timeAgoSinceDate(result!)
cell.timeLabel.text = timeDate
cell.commentBtn.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
for person in self.posts[inverseIndex].peopleWhoLike{
if person == Auth.auth().currentUser!.uid{
cell.unlikeBtn.isHidden = false
cell.likeBtn.isHidden = true
delegate?.updateButtons(likeIt: person == Auth.auth().currentUser?.uid)
break
}
}
if cell.likeBtn.isHidden == true{
delegate?.updateButtons(likeIt: false)
}else{
delegate?.updateButtons(likeIt: true)
}
cell.indexPath = indexPath
cell.delegate = self
return cell
}
@objc func buttonClicked(sender:UIButton)
{
}
func commentButtonTapped(at index: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "PostCommentController")
as? PostCommentController
let inverseIndex = self.posts.count - index.row - 1
let string = self.posts[inverseIndex].timeAgo
let df = DateFormatter()
df.dateFormat = "yyyy/MM/dd, H:mm:ss"
let result = df.date(from: string!)
let timeDate = timeAgoSinceDate(result!)
vc?.postID = self.posts[inverseIndex].postID
print(self.posts[inverseIndex].postID)
vc?.authorName = self.posts[inverseIndex].author
vc?.authorPic = self.posts[inverseIndex].authorImage
vc?.postPic = self.posts[inverseIndex].pathToImage
vc?.likesText = "\(self.posts[inverseIndex].likes!) Likes"
vc?.time = timeDate
vc?.likesCount = self.posts[inverseIndex].peopleWhoLike
self.present(vc!, animated: true, completion: nil)
}
@IBAction func unwindToViewController1(_ sender: UIStoryboardSegue) {
print("I just unwind")
}
}
vc2:
import UIKit
import Firebase
class PostCommentController: UIViewController, UITableViewDelegate, UITableViewDataSource, UpdateVC1 {
func updateButtons(likeIt: Bool) {
likeBtn.isHidden = !likeIt
unlikeBtn.isHidden = likeIt
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? NewsViewController {
destination.delegate = self
}
}
@IBOutlet weak var tableview: UITableView!
@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 authorImage: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var backButton: UIBarButtonItem!
var postID: String!
var authorName = ""
var authorPic = ""
var postPic = ""
var likesText = ""
var time = ""
var likesCount: [String] = []
@IBAction func likePressed(_ sender: Any) {
self.likeBtn.isEnabled = false
let ref = Database.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!)" :
Auth.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
}
}
})
}else{
}
})
}
})
ref.removeAllObservers()
}
@IBAction func unlikePressed(_ sender: Any) {
self.unlikeBtn.isEnabled = false
let ref = Database.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 == Auth.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()
}
// @IBAction func backButton(_ sender: Any) {
// let tabVC = UIStoryboard(name: "Main", bundle: nil)
// .instantiateViewController(withIdentifier: "NavigationTab") as! UITabBarController
// tabVC.selectedIndex = 0
// self.present(tabVC, animated: true, completion: nil)
// }
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
authorLabel.text = authorName
authorImage.downloadImage(from: authorPic)
postImage.downloadImage(from: postPic)
likeLabel.text = likesText
timeLabel.text = time
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
for person in likesCount{
if person == Auth.auth().currentUser!.uid{
unlikeBtn.isHidden = false
likeBtn.isHidden = true
break
}
}
}
}
PostCell:
import UIKit
import Firebase
protocol commentButtonDelegate {
func commentButtonTapped(at index: IndexPath)
}
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 authorImage: UIImageView!
@IBOutlet weak var commentBtn: UIButton!
@IBOutlet weak var timeLabel: UILabel!
var postID: String!
var delegate: commentButtonDelegate!
@IBAction func likePressed(_ sender: Any) {
self.likeBtn.isEnabled = false
let ref = Database.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!)" :
Auth.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
}
}
})
}else{
print(post)
}
})
}
})
ref.removeAllObservers()
}
@IBAction func unlikePressed(_ sender: Any) {
self.unlikeBtn.isEnabled = false
let ref = Database.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 == Auth.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()
}
var indexPath: IndexPath!
@IBAction func commentBtn(_ sender: UIButton) {
self.delegate?.commentButtonTapped(at: indexPath)
}
var userID: String!
}