Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // CommentVC.swift
- // VolumeiOS
- //
- // Created by Dillon Davis on 6/13/20.
- // Copyright © 2020 Dillon Davis. All rights reserved.
- //
- import Foundation
- import UIKit
- struct CommentStruct {
- static var isSelected:Bool? = false
- static var subCommentReplySelected:Bool? = false
- static var parent_id:String?
- func updateIsSelected(newBool: Bool) {
- CommentStruct.self.isSelected = newBool
- }
- func updateParentId(newString: String) {
- CommentStruct.self.parent_id = newString
- }
- func updatesubReplyIsSelected(newBool: Bool) {
- CommentStruct.self.subCommentReplySelected = newBool
- }
- }
- protocol TableViewSubCommentDelegate {
- func didSendSubComment(parent_id:String)
- }
- protocol TableViewDelegate: class {
- func didSendSubComment()
- }
- class CommentVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate, UpdateTableView {
- func updateTableView(bool: Bool) {
- if bool == true {
- UIView.performWithoutAnimation {
- self.myTableView.beginUpdates()
- self.myTableView.endUpdates()
- }
- }
- }
- private var myTableView:UITableView!
- var textField = UITextField()
- var bottomConstraint:NSLayoutConstraint?
- var profile = SessionManager.shared.profile
- var username:String?
- var imageLoader:DownloadImage?
- var comments:[CommentViewModel] = []
- var sub_comments:[CommentViewModel] = []
- var textViewHeight = CGFloat()
- let countLabel = UILabel()
- let textViewView = UIView()
- let sendBtn = UIButton()
- var tap: UITapGestureRecognizer?
- let comment = CommentStruct()
- var parent_id:String?
- var reply:Bool = false
- var subReply:Bool = false
- var delegate:TableViewSubCommentDelegate?
- weak var delegate2:TableViewDelegate?
- var usernameReply:String?
- var index:IndexPath?
- var replyingCommentCell: CommentCell?
- lazy var textView:UITextView = {
- let tv = UITextView()
- tv.isScrollEnabled = false
- tv.text = "Enter Comment"
- tv.textColor = UIColor.lightGray
- tv.sizeToFit()
- tv.returnKeyType = UIReturnKeyType.default
- tv.layer.cornerRadius = 4
- tv.layer.borderColor = UIColor.lightGray.cgColor
- tv.layer.borderWidth = 0.5
- tv.keyboardType = UIKeyboardType.default
- tv.backgroundColor = UIColor.white
- tv.textContainer.maximumNumberOfLines = 0
- tv.textContainer.lineBreakMode = .byCharWrapping
- tv.font = UIFont(name: "GillSans", size: 18)
- return tv
- }()
- override func viewDidLoad() {
- view.backgroundColor = UIColor.white
- navigationController?.isToolbarHidden = true
- getUser()
- self.textView.delegate = self
- view.addSubview(self.textViewView)
- view.bringSubviewToFront(self.textViewView)
- textViewView.addSubview(textView)
- textViewView.addSubview(sendBtn)
- sendBtn.isEnabled = false
- createViewForTextView()
- setupTextViewConstraints()
- createSendButton()
- addTableView()
- loadComments()
- view.isUserInteractionEnabled = true
- tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
- if let tap = tap {
- view.addGestureRecognizer(tap)
- }
- NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
- }
- func getUser() {
- if let id = profile?.sub {
- print("profile?.sub id \(profile?.sub)")
- GetUsersById(id: id).getAllPosts {
- self.username = $0[0].username
- print("self.username \(self.username)")
- }
- } else {
- print("profile?.sub \(profile?.sub)")
- }
- }
- func setupCountLabel() {
- countLabel.textColor = UIColor.black
- countLabel.textAlignment = .center
- countLabel.layer.cornerRadius = 5
- countLabel.layer.borderWidth = 1.0
- countLabel.backgroundColor = UIColor.white
- countLabel.layer.borderColor = UIColor.lightGray.cgColor
- view.addSubview(countLabel)
- countLabel.translatesAutoresizingMaskIntoConstraints = false
- countLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
- countLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
- countLabel.bottomAnchor.constraint(equalTo: textView.topAnchor).isActive = true
- countLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
- }
- func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
- if CommentStruct.isSelected! && reply {
- textView.text = nil
- textView.textColor = UIColor.black
- reply = false
- }
- if CommentStruct.subCommentReplySelected! && subReply {
- textView.text = nil
- textView.textColor = UIColor.black
- subReply = false
- }
- if text == "\n" {
- textView.resignFirstResponder()
- return false
- }
- countLabel.text = "\(textView.text.count)"
- return textView.text.count + (text.count - range.length) <= 250
- }
- func textViewDidBeginEditing(_ textView: UITextView) {
- textView.text = nil
- textView.textColor = UIColor.black
- }
- func textViewDidChange(_ textView: UITextView) {
- if textView.text == "" {
- sendBtn.isEnabled = false
- } else {
- sendBtn.isEnabled = true
- }
- }
- func textViewDidEndEditing(_ textView: UITextView) {
- if textView.text == "" {
- textView.text = "Enter Comment"
- textView.textColor = UIColor.lightGray
- }
- }
- @objc func dismissKeyboard() {
- textView.resignFirstResponder()
- if textView.text == "Reply" && self.textView.textColor == UIColor.lightGray {
- textView.text = "Enter Comment"
- textView.textColor = UIColor.lightGray
- }
- if textView.text == "" {
- textView.text = "Enter Comment"
- textView.textColor = UIColor.lightGray
- }
- print("dismissKeyBoard")
- }
- @objc func handleKeyBoardNotification(notification:NSNotification) {
- if let userInfo = notification.userInfo {
- let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
- let isKeyBoardShowing = notification.name == UIResponder.keyboardWillShowNotification
- bottomConstraint?.constant = isKeyBoardShowing ? -keyboardFrame.height : 0
- UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
- self.view.layoutIfNeeded()
- }) { (completed) in
- }
- }
- }
- func loadComments() {
- let getComments = GETComments(id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", path: "comments")
- getComments.getAllById { comments in
- self.comments = comments.map { comment in
- let ret = CommentViewModel()
- ret.mainComment = comment
- return ret
- }
- self.myTableView.reloadData()
- }
- }
- func addTableView() {
- self.myTableView = UITableView()
- self.myTableView?.translatesAutoresizingMaskIntoConstraints = false
- self.myTableView.frame.size.height = self.view.frame.height
- self.myTableView.frame.size.width = self.view.frame.width
- self.myTableView.register(CommentCell.self, forCellReuseIdentifier: "MyCell")
- self.myTableView.dataSource = self
- self.myTableView.delegate = self
- self.myTableView.isScrollEnabled = true
- myTableView.delaysContentTouches = false
- self.view.addSubview(self.myTableView)
- self.myTableView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
- self.myTableView?.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
- self.myTableView?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
- self.myTableView.bottomAnchor.constraint(equalTo: self.textView.topAnchor).isActive = true
- self.myTableView.estimatedRowHeight = 80
- self.myTableView.rowHeight = UITableView.automaticDimension
- myTableView.layoutMargins = UIEdgeInsets.zero
- myTableView.separatorInset = UIEdgeInsets.zero
- }
- func setupTextViewConstraints() {
- textView.translatesAutoresizingMaskIntoConstraints = false
- textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
- textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
- textView.topAnchor.constraint(equalTo: textViewView.topAnchor).isActive = true
- var frame = self.textView.frame
- frame.size.height = self.textView.contentSize.height
- self.textView.frame = frame
- }
- func createViewForTextView() {
- textViewView.backgroundColor = UIColor.white
- textViewView.layer.borderColor = UIColor.lightGray.cgColor
- textViewView.layer.borderWidth = 1.0
- textViewView.translatesAutoresizingMaskIntoConstraints = false
- textViewView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
- textViewView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
- textViewView.heightAnchor.constraint(equalTo: textView.heightAnchor, constant: 50).isActive = true
- bottomConstraint = textViewView.bottomAnchor.constraint(equalTo: (self.view.safeAreaLayoutGuide.bottomAnchor), constant: 0)
- bottomConstraint?.isActive = true
- }
- func createSendButton() {
- let btnConfiguration = UIImage.SymbolConfiguration(scale: .medium)
- let btnSymbolImage = UIImage(systemName: "arrowshape.turn.up.right.fill", withConfiguration: btnConfiguration)
- sendBtn.setImage(btnSymbolImage, for: .normal)
- sendBtn.translatesAutoresizingMaskIntoConstraints = false
- sendBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true
- sendBtn.widthAnchor.constraint(equalToConstant: 30).isActive = true
- sendBtn.trailingAnchor.constraint(equalTo: textViewView.trailingAnchor, constant: -8).isActive = true
- sendBtn.bottomAnchor.constraint(equalTo: self.textViewView.bottomAnchor, constant: -15).isActive = true
- sendBtn.addTarget(self, action: #selector(sendComment), for: .touchUpInside)
- }
- @objc func sendComment() {
- if CommentStruct.isSelected == true {
- print("true isSelected")
- sendSubComment()
- } else if CommentStruct.subCommentReplySelected == true {
- sendSubCommentReply()
- } else {
- print("false not selected")
- performActionSend()
- }
- view.endEditing(true)
- }
- func sendSubComment() {
- if let text = textView.text,
- let username = self.username,
- let user_picture = profile?.picture,
- let user_id = profile?.sub,
- let parent_id = parent_id {
- let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text: text, parent_id: parent_id)
- let postRequest = CommentPostRequest(endpoint: "sub_comment")
- postRequest.save(comment) { (result) in
- switch result {
- case .success(let comment):
- let viewModel = CommentViewModel()
- self.delegate?.didSendSubComment(parent_id: parent_id)
- print("self.delegate2 \(self.delegate2)")
- print("delegate tableview \(self.delegate)")
- DispatchQueue.main.async {
- self.replyingCommentCell?.addedSubComment()
- self.delegate2?.didSendSubComment()
- print("self.delegate2 \(self.delegate2) main async")
- self.myTableView.reloadData()
- UIView.performWithoutAnimation {
- self.myTableView.beginUpdates()
- self.myTableView.endUpdates()
- }
- }
- case .failure(let error):
- print("An error occurred: \(error)")
- }
- }
- } else {
- print("text \(textView.text)")
- print("username \(self.username)")
- print("user_picture \(profile?.picture)")
- print("user_id \(profile?.sub)")
- print("parent_id \(parent_id)")
- }
- textView.text = ""
- }
- func sendSubCommentReply() {
- if let text = textView.text,
- let username = self.username,
- let user_picture = profile?.picture,
- let user_id = profile?.sub,
- let parent_id = parent_id,
- let usernameReply = usernameReply {
- let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text:
- "Reply To @\(usernameReply): \(text)", parent_id: parent_id)
- let postRequest = CommentPostRequest(endpoint: "sub_comment")
- postRequest.save(comment) { (result) in
- switch result {
- case .success(let comment):
- var viewModel = CommentViewModel()
- self.delegate?.didSendSubComment(parent_id: parent_id)
- print("delegate tableview \(self.delegate)")
- DispatchQueue.main.async {
- self.replyingCommentCell?.addedSubComment()
- self.myTableView.reloadData()
- UIView.performWithoutAnimation {
- self.myTableView.beginUpdates()
- self.myTableView.endUpdates()
- }
- }
- case .failure(let error):
- print("An error occurred: \(error)")
- }
- }
- } else {
- print("text \(textView.text)")
- print("username \(username)")
- print("user_picture \(profile?.picture)")
- print("user_id \(profile?.sub)")
- print("parent_id \(parent_id)")
- }
- textView.text = ""
- }
- func performActionSend() {
- if let text = textView.text,
- let username = username,
- let user_picture = profile?.picture,
- let user_id = profile?.sub {
- let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text: text, parent_id: nil)
- let postRequest = CommentPostRequest(endpoint: "comment")
- postRequest.save(comment) { (result) in
- switch result {
- case .success(let comment):
- print("the following comment has been sent: \(comment)")
- self.loadComments()
- case .failure(let error):
- print("An error occurred: \(error)")
- }
- }
- } else {
- print("text \(textView.text)")
- print("username \(username)")
- print("user_picture \(profile?.picture)")
- print("user_id \(profile?.sub)")
- }
- textView.text = ""
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return comments.count
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) as! CommentCell
- cell.delegate = self
- cell.delegate2 = self
- cell.selectionStyle = .none
- cell.index = indexPath
- cell.commentDelegate = self
- let item = comments[indexPath.item]
- cell.viewModel = item
- return cell
- }
- }
- extension CommentVC: CommentCellDelegate {
- func didTapReplyBtn(parent_id: String, cell: CommentCell) {
- if !textView.isFirstResponder {
- textView.becomeFirstResponder()
- comment.updateIsSelected(newBool: true)
- self.replyingCommentCell = cell
- reply = true
- self.parent_id = parent_id
- textView.text = nil
- if textView.text.isEmpty {
- textView.text = "Reply"
- textView.textColor = UIColor.lightGray
- textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
- }
- } else {
- textView.text = nil
- textView.resignFirstResponder()
- if textView.text.isEmpty {
- textView.text = "Enter Comment"
- textView.textColor = UIColor.lightGray
- }
- }
- }
- }
- extension CommentVC: CommentCellDelegate2 {
- func didTapSubReplyBtn(username: String, parent_id:String, cell: CommentCell) {
- if !textView.isFirstResponder {
- textView.becomeFirstResponder()
- comment.updateIsSelected(newBool: false)
- comment.updatesubReplyIsSelected(newBool: true)
- subReply = true
- self.parent_id = parent_id
- self.usernameReply = username
- self.replyingCommentCell = cell
- textView.text = nil
- if textView.text.isEmpty {
- textView.text = "Reply"
- textView.textColor = UIColor.lightGray
- textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
- }
- } else {
- textView.text = nil
- textView.resignFirstResponder()
- if textView.text.isEmpty {
- textView.text = "Enter Comment"
- textView.textColor = UIColor.lightGray
- }
- }
- }
- }
- import Foundation
- import UIKit
- import Combine
- protocol UpdateTableView: class {
- func updateTableView(bool: Bool)
- }
- protocol CommentViewDelegate: class {
- func subCommentLikePressed(sender: UIButton)
- func replyToSubComment(sender: UIButton)
- }
- class CommentView: UIView {
- weak var delegate: CommentViewDelegate?
- override init(frame: CGRect) {
- super.init(frame: frame)
- addSubview(user_image)
- addSubview(username)
- addSubview(textView)
- addSubview(likeBtn)
- addSubview(numberOfLikes)
- addSubview(replyBtn)
- replyBtnConstraints()
- setImageConstraints()
- setUsernameConstraints()
- textViewContstraints()
- commentLikeBtnConstraints()
- commentLikesConstraints()
- }
- required init?(coder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- lazy var replyBtn:UIButton = {
- let btn = UIButton()
- btn.setTitle("Reply", for: .normal)
- btn.setTitleColor(UIColor.gray, for: .normal)
- btn.titleLabel?.font = .systemFont(ofSize: 12)
- btn.contentHorizontalAlignment = .left
- btn.addTarget(self, action: #selector(replyToSubComment(sender:)), for: .touchUpInside)
- return btn
- }()
- lazy var likeBtn:UIButton = {
- let btn = UIButton()
- let symbol = UIImage(systemName: "heart")
- btn.setImage(symbol , for: .normal)
- btn.tintColor = UIColor.darkGray
- btn.isUserInteractionEnabled = true
- btn.addTarget(self, action: #selector(subCommentLikePressed(sender:)), for: .touchUpInside)
- return btn
- }()
- var numberOfLikes:UILabel = {
- let label = UILabel()
- label.textAlignment = .center
- label.text = "0"
- return label
- }()
- lazy var textView:UITextView = {
- let tv = UITextView()
- tv.isScrollEnabled = false
- tv.isEditable = false
- tv.sizeToFit()
- tv.backgroundColor = UIColor.lightGray
- tv.textContainer.maximumNumberOfLines = 0
- tv.textContainer.lineBreakMode = .byCharWrapping
- tv.font = UIFont(name: "GillSans", size: 18)
- return tv
- }()
- lazy var user_image: UIImageView = {
- let image = UIImageView()
- return image
- }()
- lazy var username:UILabel = {
- let label = UILabel()
- label.textColor = UIColor.gray
- label.font = UIFont.systemFont(ofSize: 14)
- return label
- }()
- @objc func subCommentLikePressed(sender:UIButton) {
- print("delegate \(delegate)")
- if let delegate = delegate {
- delegate.subCommentLikePressed(sender: sender)
- }
- }
- @objc func replyToSubComment(sender:UIButton) {
- print("delegate \(delegate)")
- if let delegate = delegate {
- delegate.replyToSubComment(sender: sender)
- }
- }
- func replyBtnConstraints() {
- replyBtn.translatesAutoresizingMaskIntoConstraints = false
- replyBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
- replyBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
- replyBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
- replyBtn.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 1).isActive = true
- replyBtn.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
- }
- func commentLikesConstraints() {
- numberOfLikes.translatesAutoresizingMaskIntoConstraints = false
- numberOfLikes.widthAnchor.constraint(equalToConstant: 60).isActive = true
- numberOfLikes.heightAnchor.constraint(equalToConstant: 30).isActive = true
- numberOfLikes.centerXAnchor.constraint(equalTo: likeBtn.centerXAnchor).isActive = true
- numberOfLikes.topAnchor.constraint(equalTo: likeBtn.bottomAnchor, constant: -5).isActive = true
- }
- func commentLikeBtnConstraints() {
- likeBtn.translatesAutoresizingMaskIntoConstraints = false
- likeBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
- likeBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
- likeBtn.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
- likeBtn.topAnchor.constraint(equalTo: textView.topAnchor, constant: -5).isActive = true
- }
- func setImageConstraints() {
- user_image.translatesAutoresizingMaskIntoConstraints = false
- user_image.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
- user_image.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8).isActive = true
- user_image.heightAnchor.constraint(equalToConstant: 40).isActive = true
- user_image.widthAnchor.constraint(equalToConstant: 40).isActive = true
- }
- func setUsernameConstraints() {
- username.translatesAutoresizingMaskIntoConstraints = false
- username.topAnchor.constraint(equalTo: user_image.topAnchor, constant: 5).isActive = true
- username.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
- username.heightAnchor.constraint(equalToConstant: 10).isActive = true
- username.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
- }
- func textViewContstraints() {
- textView.translatesAutoresizingMaskIntoConstraints = false
- textView.topAnchor.constraint(equalTo: username.bottomAnchor, constant: 5).isActive = true
- textView.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
- textView.trailingAnchor.constraint(equalTo: likeBtn.leadingAnchor, constant: -3).isActive = true
- }
- }
- extension UITableViewCell {
- var tableView: UITableView? {
- var p = self.superview
- while p != nil {
- if let t = p as? UITableView {
- return t
- }
- p = p?.superview
- }
- return nil
- }
- func viewContentLayoutIfNeed() {
- self.tableView?.beginUpdates()
- self.tableView?.endUpdates()
- }
- func viewContentSetNeedsDisplay() {
- UIView.performWithoutAnimation {
- self.tableView?.beginUpdates()
- self.tableView?.endUpdates()
- }
- }
- }
- protocol CommentCellDelegate {
- func didTapReplyBtn(parent_id: String, cell: CommentCell)
- }
- protocol CommentCellDelegate2: class {
- func didTapSubReplyBtn(username:String, parent_id:String, cell: CommentCell)
- }
- class CommentCell:UITableViewCell {
- static var shared = CommentCell()
- var imageLoader:DownloadImage?
- var user_image = UIImageView()
- var username = UILabel()
- var stackView = UIStackView()
- var sub_comments:[Comments] = []
- var bottomConstraint:NSLayoutConstraint?
- var svBottomAnchor:NSLayoutConstraint?
- var parent_id:String?
- var user_id:String?
- var offset:Int?
- weak var delegate:UpdateTableView?
- weak var delegate2:CommentCellDelegate2?
- var commentDelegate:CommentCellDelegate?
- let comment_view = CommentView()
- var liked:Bool = false
- var subCommentView:CommentView?
- var profile = SessionManager.shared.profile
- var index:IndexPath?
- var commentsExist:Bool?
- var viewModel: CommentViewModel? {
- didSet {
- if let item = viewModel {
- print("didSet cell")
- if let id = item.mainComment?.id, let user_id = profile?.sub {
- parent_id = id
- item.loadCommentLikes(id: id)
- item.getCommentLikesBuIserId(comment_id: id, user_id: user_id)
- item.commentsExist(comment_id: id, offset: "0", completion: {_ in
- if item.subComments.isEmpty && item.repliesExist != false {
- print("item.repliesExist != false")
- self.repliesBtn.isHidden = false
- self.repliesBtn.isEnabled = true
- self.viewMoreBtn.isHidden = true
- } else {
- print("item.repliesExist != true")
- }
- })
- }
- imageLoader = DownloadImage()
- imageLoader?.imageDidSet = { [weak self] image in
- self?.user_image.image = image
- }
- if let picture = item.mainComment?.user_picture {
- imageLoader?.downloadImage(urlString: picture)
- }
- username.text = item.mainComment?.username
- textView.text = item.mainComment?.text
- stackView.arrangedSubviews.forEach {
- stackView.removeArrangedSubview($0)
- $0.removeFromSuperview()
- }
- if item.commentsExist == false {
- viewMoreBtn.isHidden = true
- viewMoreBtn.isEnabled = false
- }
- item.commentsExistDidInserts = { [weak self] bool in
- if bool == false {
- self?.viewMoreBtn.isHidden = true
- self?.viewMoreBtn.isEnabled = false
- }
- }
- item.subComments.forEach { subComment in
- subCommentView = CommentView()
- self.subCommentView?.delegate = self
- subCommentView?.textView.text = subComment.text
- print("subComment.text \(subComment.text)")
- imageLoader?.imageDidSet = { [weak self] image in
- self?.subCommentView?.user_image.image = image
- }
- if let picture = subComment.user_picture {
- imageLoader?.downloadImage(urlString: picture)
- }
- subCommentView?.username.text = subComment.username
- if let firstIndex = item.subComments.firstIndex(where: { $0.id == subComment.id }) {
- subCommentView?.likeBtn.tag = firstIndex
- }
- if subComment.isliked == true {
- let image = UIImage(systemName: "heart.fill")
- subCommentView?.likeBtn.setImage(image, for: .normal)
- subCommentView?.likeBtn.tintColor = .red
- }
- if let numberOfLikes = subComment.numberOfLikes {
- subCommentView?.numberOfLikes.text = "\(numberOfLikes)"
- }
- if let commentView = subCommentView {
- stackView.addArrangedSubview(commentView)
- }
- }
- viewMoreBtn.isUserInteractionEnabled = true
- repliesBtn.isUserInteractionEnabled = true
- item.likeBtnImageDidSet = { [weak self] in self?.likeBtn.setImage($0, for: .normal) }
- item.likeBtnTintColorDidSet = { [weak self] in self?.likeBtn.tintColor = $0 }
- item.subCommentDidInserts = { [weak self] insertedSubComments in
- guard let `self` = self else { return }
- insertedSubComments.forEach { subComment in
- let subCommentView = CommentView()
- subCommentView.delegate = self
- subCommentView.textView.text = subComment.text
- self.imageLoader?.imageDidSet = { [weak self] image in
- subCommentView.user_image.image = image
- }
- if let picture = subComment.user_picture {
- self.imageLoader?.downloadImage(urlString: picture)
- }
- subCommentView.username.text = subComment.username
- if let firstIndex = item.subComments.firstIndex(where: { $0.id == subComment.id }) {
- subCommentView.likeBtn.tag = firstIndex
- subCommentView.numberOfLikes.tag = firstIndex
- }
- self.stackView.addArrangedSubview(subCommentView)
- if let comment_id = subComment.id, let user_id = self.profile?.sub {
- item.getSubCommentLikesByIserId(comment_id: comment_id, user_id: user_id) { [weak subCommentView] bool in
- if bool == true {
- let image = UIImage(systemName: "heart.fill")
- subCommentView?.likeBtn.setImage(image, for: .normal)
- subCommentView?.likeBtn.tintColor = .red
- if let index = subCommentView?.likeBtn.tag {
- item.subComments[index].isliked = true
- }
- } else {
- if let index = subCommentView?.likeBtn.tag {
- item.subComments[index].isliked = false
- }
- }
- }
- }
- if let id = subComment.id {
- item.loadSubCommentLikes(id: id) {[weak subCommentView] likes in
- if let index = subCommentView?.likeBtn.tag {
- item.subComments[index].numberOfLikes = likes.count
- }
- subCommentView?.numberOfLikes.text = "\(likes.count)"
- }
- }
- }
- UIView.animate(withDuration: 0.5, animations: {
- self.stackView.isHidden = false
- self.stackView.alpha = 1
- })
- self.viewMoreBtn.setTitle("View More", for: .normal)
- self.viewMoreBtn.isUserInteractionEnabled = true
- if item.commentsExist != false {
- self.viewMoreBtn.isHidden = false
- self.viewMoreBtn.isEnabled = true
- }
- self.repliesBtn.setTitle("View Replies", for: .normal)
- self.repliesBtn.isUserInteractionEnabled = true
- self.repliesBtn.isHidden = true
- self.viewContentLayoutIfNeed()
- }
- self.numberOfLikes.text = String(item.commentLikes.count)
- item.commentLikesDidInserts = { [weak self] likes in
- self?.numberOfLikes.text = String(likes.count)
- }
- }
- }
- }
- var components:URLComponents = {
- var component = URLComponents()
- component.scheme = "http"
- component.host = "localhost"
- component.port = 8000
- return component
- }()
- lazy var textView:UITextView = {
- let tv = UITextView()
- tv.isScrollEnabled = false
- tv.isEditable = false
- tv.sizeToFit()
- tv.backgroundColor = UIColor.lightGray
- tv.textContainer.maximumNumberOfLines = 0
- tv.textContainer.lineBreakMode = .byCharWrapping
- tv.font = UIFont(name: "GillSans", size: 18)
- return tv
- }()
- lazy var likeBtn:UIButton = {
- let btn = UIButton()
- let symbolConfig = UIImage.SymbolConfiguration(pointSize: 25.0, weight: .medium, scale: .medium)
- let symbol = UIImage(systemName: "heart", withConfiguration: symbolConfig)
- btn.setImage(symbol , for: .normal)
- btn.tintColor = UIColor.darkGray
- btn.addTarget(self, action: #selector(commentLikePressed), for: .touchUpInside)
- return btn
- }()
- lazy var numberOfLikes:UILabel = {
- let label = UILabel()
- label.textAlignment = .center
- label.text = "0"
- return label
- }()
- lazy var mainReplyBtn:UIButton = {
- let btn = UIButton()
- btn.setTitle("Reply", for: .normal)
- btn.setTitleColor(UIColor.gray, for: .normal)
- btn.titleLabel?.font = .systemFont(ofSize: 12)
- btn.contentHorizontalAlignment = .left
- btn.addTarget(self, action: #selector(mainCommentReplyPressed), for: .touchUpInside)
- return btn
- }()
- lazy var repliesBtn:UIButton = {
- let btn = UIButton()
- btn.setTitle("View Replies", for: .normal)
- btn.setTitleColor(UIColor.gray, for: .normal)
- btn.titleLabel?.font = .systemFont(ofSize: 12)
- btn.contentHorizontalAlignment = .left
- btn.isHidden = true
- btn.isEnabled = false
- btn.addTarget(self, action: #selector(repliesBtnPressed), for: .touchUpInside)
- return btn
- }()
- lazy var viewMoreBtn:UIButton = {
- let btn = UIButton()
- btn.setTitle("View More", for: .normal)
- btn.setTitleColor(UIColor.gray, for: .normal)
- btn.titleLabel?.font = .systemFont(ofSize: 12)
- btn.contentHorizontalAlignment = .left
- btn.isHidden = true
- btn.isEnabled = false
- btn.addTarget(self, action: #selector(viewMorePressed), for: .touchUpInside)
- return btn
- }()
- override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
- super.init(style: style, reuseIdentifier: reuseIdentifier)
- addSubview(user_image)
- setImageConstraints()
- setUsername()
- addSubview(username)
- setUsernameConstraints()
- addSubview(textView)
- addSubview(mainReplyBtn)
- addSubview(repliesBtn)
- addSubview(viewMoreBtn)
- addSubview(likeBtn)
- addSubview(numberOfLikes)
- configureStackView()
- textViewContstraints()
- commentLikeBtnConstraints()
- commentLikesConstraints()
- mainCommentReplyBtnConstraints()
- print("Text view bottomAnchor init \(textView.bottomAnchor.description)")
- setStackViewContstraints()
- repliesBtnConstraints()
- viewMoreBtnConstraints()
- }
- required init?(coder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- func addedSubComment() {
- if let id = self.parent_id, let user_id = profile?.sub {
- self.viewModel?.loadSubCommentsAfterReply(comment_id: id, user_id: user_id)
- }
- }
- @objc func commentLikePressed() {
- guard let viewModel = viewModel else { return }
- if viewModel.isLiked {
- if let comment_id = parent_id, let user_id = profile?.sub {
- viewModel.unlikeComment(comment_id: comment_id, user_id: user_id)
- }
- } else {
- if let user_id = profile?.sub, let comment_id = parent_id {
- viewModel.likeComment(user_id: user_id, comment_id: comment_id)
- }
- }
- }
- @objc func mainCommentReplyPressed() {
- if let parent_id = parent_id {
- commentDelegate?.didTapReplyBtn(parent_id: parent_id, cell: self)
- }
- }
- @objc func repliesBtnPressed() {
- repliesBtn.setTitle("Loading...", for: .normal)
- repliesBtn.isUserInteractionEnabled = false
- if let id = self.parent_id {
- viewModel?.updateParentId(newString: id)
- viewModel?.reply(id:id, completion: {
- self.repliesBtn.isHidden = true
- if self.viewModel?.commentsExist != false {
- self.viewMoreBtn.isHidden = false
- self.viewMoreBtn.isEnabled = true
- }
- })
- }
- }
- @objc func viewMorePressed() {
- viewMoreBtn.setTitle("Loading...", for: .normal)
- viewMoreBtn.isUserInteractionEnabled = false
- if let id = self.parent_id {
- viewModel?.updateParentId(newString: id)
- viewModel?.viewMore(id: id, completion: {
- if self.viewModel?.commentsExist != false {
- self.viewMoreBtn.isHidden = false
- self.viewMoreBtn.isEnabled = true
- }
- })
- }
- }
- func configureStackView() {
- addSubview(stackView)
- stackView.axis = .vertical
- stackView.distribution = .fillProportionally
- stackView.spacing = 5
- }
- func commentLikesConstraints() {
- numberOfLikes.translatesAutoresizingMaskIntoConstraints = false
- numberOfLikes.widthAnchor.constraint(equalToConstant: 60).isActive = true
- numberOfLikes.heightAnchor.constraint(equalToConstant: 30).isActive = true
- numberOfLikes.centerXAnchor.constraint(equalTo: likeBtn.centerXAnchor).isActive = true
- numberOfLikes.topAnchor.constraint(equalTo: likeBtn.bottomAnchor, constant: -5).isActive = true
- }
- func commentLikeBtnConstraints() {
- likeBtn.translatesAutoresizingMaskIntoConstraints = false
- likeBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
- likeBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
- likeBtn.leadingAnchor.constraint(equalTo: textView.trailingAnchor, constant: 3).isActive = true
- likeBtn.topAnchor.constraint(equalTo: textView.topAnchor, constant: -5).isActive = true
- }
- func mainCommentReplyBtnConstraints() {
- mainReplyBtn.translatesAutoresizingMaskIntoConstraints = false
- mainReplyBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
- mainReplyBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
- mainReplyBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
- mainReplyBtn.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 1).isActive = true
- }
- func setStackViewContstraints() {
- stackView.translatesAutoresizingMaskIntoConstraints = false
- stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -30).isActive = true
- stackView.topAnchor.constraint(equalTo: mainReplyBtn.bottomAnchor, constant: 42).isActive = true
- stackView.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
- stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
- }
- func setImageConstraints() {
- user_image.translatesAutoresizingMaskIntoConstraints = false
- user_image.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
- user_image.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8).isActive = true
- user_image.heightAnchor.constraint(equalToConstant: 40).isActive = true
- user_image.widthAnchor.constraint(equalToConstant: 40).isActive = true
- }
- func setUsername() {
- username.textColor = UIColor.gray
- username.font = UIFont.systemFont(ofSize: 14)
- }
- func setUsernameConstraints() {
- username.translatesAutoresizingMaskIntoConstraints = false
- username.topAnchor.constraint(equalTo: user_image.topAnchor, constant: 5).isActive = true
- username.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
- username.heightAnchor.constraint(equalToConstant: 10).isActive = true
- username.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
- }
- func textViewContstraints() {
- textView.translatesAutoresizingMaskIntoConstraints = false
- textView.topAnchor.constraint(equalTo: username.bottomAnchor, constant: 5).isActive = true
- textView.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
- textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -60).isActive = true
- }
- func repliesBtnConstraints() {
- repliesBtn.translatesAutoresizingMaskIntoConstraints = false
- bottomConstraint =
- repliesBtn.bottomAnchor.constraint(equalTo: stackView.topAnchor)
- bottomConstraint?.isActive = true
- repliesBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
- repliesBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
- repliesBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
- repliesBtn.topAnchor.constraint(equalTo: mainReplyBtn.bottomAnchor).isActive = true
- }
- func viewMoreBtnConstraints() {
- viewMoreBtn.translatesAutoresizingMaskIntoConstraints = false
- viewMoreBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
- viewMoreBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true
- viewMoreBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor, constant: 5).isActive = true
- viewMoreBtn.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 9).isActive = true
- }
- }
- extension CommentCell: CommentViewDelegate {
- func replyToSubComment(sender: UIButton) {
- let subCommentView = sender.superview as! CommentView
- if let username = subCommentView.username.text, let parent_id = parent_id {
- delegate2?.didTapSubReplyBtn(username: username, parent_id: parent_id, cell: self)
- }
- }
- @objc func subCommentLikePressed(sender:UIButton) {
- var comment_id:String?
- comment_id = viewModel?.subComments[sender.tag].id
- guard let viewModel = viewModel else { return }
- if viewModel.subComments[sender.tag].isliked == true {
- if let user_id = profile?.sub, let comment_id = comment_id {
- viewModel.unlikeSubComment(comment_id: comment_id, user_id: user_id, completion: {
- DispatchQueue.main.async {
- if let id = viewModel.subComments[sender.tag].id {
- viewModel.loadSubCommentLikes(id: "\(id)", completion: { likes in
- let subCommentView = sender.superview as! CommentView
- subCommentView.numberOfLikes.text = "\(likes.count)"
- viewModel.subComments[sender.tag].numberOfLikes = likes.count
- })
- }
- }
- })
- }
- let image = UIImage(systemName: "heart")
- sender.setImage(image, for: .normal)
- sender.tintColor = .darkGray
- viewModel.subComments[sender.tag].isliked = false
- } else if viewModel.subComments[sender.tag].isliked == false {
- if let user_id = profile?.sub, let comment_id = comment_id {
- viewModel.likeSubComment(user_id: user_id, comment_id: comment_id, completion: {
- DispatchQueue.main.async {
- if let id = viewModel.subComments[sender.tag].id {
- viewModel.loadSubCommentLikes(id: "\(id)", completion: { likes in
- let subCommentView = sender.superview as! CommentView
- subCommentView.numberOfLikes.text = "\(likes.count)"
- viewModel.subComments[sender.tag].numberOfLikes = likes.count
- })
- }
- }
- })
- let image = UIImage(systemName: "heart.fill")
- sender.setImage(image, for: .normal)
- sender.tintColor = .red
- }
- viewModel.subComments[sender.tag].isliked = true
- }
- }
- }
- import UIKit
- import Foundation
- class CommentViewModel {
- var offset: Int = 0
- static var offsetForCell: Int = 0
- var buttonTag:[Int] = []
- static var parent_id:String?
- var mainComment: Comments?
- var mainCommentImage: UIImage?
- var commentLikes: [CommentLikes] = []
- var commentLikesDidInserts: (([CommentLikes]) -> ())?
- var subComments: [Comments] = []
- var subCommentDidInserts: (([Comments]) -> ())?
- var imageDownloader: DownloadImage?
- var symbolConfig = UIImage.SymbolConfiguration(pointSize: 25.0, weight: .medium, scale: .medium)
- var likeBtnImage: UIImage? = UIImage(systemName: "heart") { didSet { likeBtnImageDidSet?(likeBtnImage) } }
- var likeBtnImageDidSet: ((UIImage?)->())?
- var likeBtnTintColor: UIColor? = UIColor.darkGray { didSet { likeBtnTintColorDidSet?(likeBtnTintColor) } }
- var likeBtnTintColorDidSet: ((UIColor?)->())?
- var isLiked: Bool = false
- var isLikedLoaded: Bool = false
- var commentsExist:Bool?
- var commentsExistDidInserts: ((Bool) -> ())?
- var repliesExist:Bool?
- var repliesExistDidInserts: ((Bool) -> ())?
- func viewMore(id: String, completion: @escaping () -> ()) {
- offset += 3
- loadSubComments()
- let offset2 = offset + 3
- commentsExist(comment_id: id, offset:"\(offset2)", completion: { comment in
- if comment.count <= 0 {
- self.commentsExist = false
- self.commentsExistDidInserts?(false)
- completion()
- }
- })
- }
- func reply(id: String, completion: @escaping () -> ()) {
- offset = 0
- loadSubComments()
- let offset2 = offset + 3
- commentsExist(comment_id: id, offset:"\(offset2)", completion: { comment in
- if comment.count <= 0 {
- self.commentsExist = false
- self.commentsExistDidInserts?(false)
- completion()
- }
- })
- }
- func loadSubComments() {
- print("loadSubComments")
- let getSubComments = GETSubComments(id: CommentViewModel.parent_id, path: "subComments", offset: "\(offset)")
- getSubComments.getAllById {
- self.subComments += $0
- self.subCommentDidInserts?($0)
- }
- }
- func commentsExist(comment_id: String, offset: String, completion: @escaping ([Comments]) -> ()) {
- let getSubComments = GETSubComments(id: comment_id, path: "subComments", offset: "\(offset)")
- getSubComments.getAllById {
- if $0.count <= 0 {
- print("commentsExist now \($0)")
- self.repliesExist = false
- self.repliesExistDidInserts?(false)
- } else {
- self.repliesExist = true
- self.repliesExistDidInserts?(true)
- }
- completion($0)
- }
- }
- func loadSubCommentsAfterReply(comment_id:String?, user_id:String?) {
- if let id = comment_id {
- let getSubComments = GETSubCommentAfterReply(id: id, user_id: user_id)
- getSubComments.getSubComment {
- self.subComments += $0
- self.subCommentDidInserts?($0)
- let offset2 = self.offset + 3
- if let comment_id = comment_id {
- self.commentsExist(comment_id: comment_id, offset:"\(offset2)", completion: { comment in
- if comment.count <= 0 {
- self.commentsExist = false
- self.commentsExistDidInserts?(false)
- }
- })
- }
- }
- }
- }
- func loadCommentLikes(id:String) {
- print("loadCommentLikes")
- let getCommentLikes = GETCommentLikes(id: id)
- getCommentLikes.getAllById {
- self.commentLikes = $0
- self.commentLikesDidInserts?($0)
- }
- }
- func getCommentLikesBuIserId(comment_id:String, user_id:String) {
- guard isLikedLoaded == false else { return }
- let getLikeByUser = GETCommentLikesByUserID(comment_id: comment_id, user_id: user_id)
- getLikeByUser.getAllById {
- if $0.count > 0 {
- self.likeBtnImage = UIImage(systemName: "heart.fill")
- self.likeBtnTintColor = .red
- self.isLiked = true
- self.isLikedLoaded = true
- }
- }
- }
- func likeComment(user_id: String, comment_id: String) {
- let commentLike = CommentLike(user_id: user_id, comment_id: comment_id)
- let postRequest = CommentLikePostRequest(endpoint: "addCommentLike")
- postRequest.save(commentLike) { (result) in
- switch result {
- case .success(let comment):
- print("the following comment like has been sent: \(commentLike)")
- self.loadCommentLikes(id: comment_id)
- case .failure(let error):
- print("An error occurred: \(error)")
- }
- }
- self.likeBtnImage = UIImage(systemName: "heart.fill")
- self.likeBtnTintColor = .red
- self.isLiked = true
- }
- func unlikeComment(comment_id: String, user_id: String) {
- let deleteRequest = DLTCommentLike(comment_id: comment_id, user_id: user_id)
- deleteRequest.delete {(err) in
- if let err = err {
- print("Failed to delete", err)
- return
- }
- self.loadCommentLikes(id: comment_id)
- print("Successfully deleted comment like from server")
- }
- self.likeBtnImage = UIImage(systemName: "heart")
- self.likeBtnTintColor = .darkGray
- self.isLiked = false
- }
- func getSubCommentLikesByIserId(comment_id:String, user_id:String, completion: @escaping (Bool) -> ()) {
- print("it worked")
- let getLikeByUser = GETCommentLikesByUserID(comment_id: comment_id, user_id: user_id)
- getLikeByUser.getAllById {
- if $0.count > 0 {
- completion(true)
- } else {
- completion(false)
- }
- }
- }
- func likeSubComment(user_id: String, comment_id: String, completion: @escaping () -> ()) {
- let commentLike = CommentLike(user_id: user_id, comment_id: comment_id)
- let postRequest = CommentLikePostRequest(endpoint: "addCommentLike")
- postRequest.save(commentLike) { (result) in
- switch result {
- case .success(let comment):
- print("the following sub comment like has been sent: \(commentLike)")
- completion()
- case .failure(let error):
- print("An error occurred: \(error)")
- }
- }
- }
- func unlikeSubComment(comment_id: String, user_id: String, completion: @escaping () -> ()) {
- let deleteRequest = DLTCommentLike(comment_id: comment_id, user_id: user_id)
- deleteRequest.delete {(err) in
- if let err = err {
- print("Failed to delete", err)
- return
- }
- completion()
- print("Successfully deleted sub comment like from server")
- }
- }
- func loadSubCommentLikes(id:String, completion: @escaping ([CommentLikes]) -> ()) {
- print("loadSubCommentLikes")
- let getCommentLikes = GETCommentLikes(id: id)
- getCommentLikes.getAllById {
- completion($0)
- }
- }
- func updateParentId(newString:String) {
- CommentViewModel.self.parent_id = newString
- }
- func updateOffsetForCell(newInt:Int) {
- CommentViewModel.self.offsetForCell = newInt
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement