Closed reginaagst closed 6 years ago
My old code needs to be updated to message kit. My question is how can I convert my old code so that I can write text hit send chat and see it in blue bubble text format.
// ChatViewController.swift // Moments1 // // Created on 8/29/18. // Copyright © 2018 All rights reserved. //
import UIKit import MessageKit import Firebase
class ChatViewController: MessagesViewController { var chat:Chat! var currentUser:User! var messages = [Message]()
// var jsqMessages = [JsqMessage]()///MessageData is just some ui stuff not our message // var outgoingBubbleImageView: JSQMessagesBubbleImage! // // var incomingBubbleImageView = JSQMessagesBubbleImage! // func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle { return .bubble } is the bubble for putting text in
var messagesRef = WADatabaseReference.messages.reference()
override func viewDidLoad() {
super.viewDidLoad()
title = chat.title
// self.setupBubbleImages() // self.setupAvatarImages() //
messagesCollectionView.messagesDataSource = self
let backButton = UIBarButtonItem(image:UIImage(named:"icon - back"),style:.plain, target:self, action:#selector(back))
self.navigationItem.leftBarButtonItem = backButton
// messagesCollectionView.messagesDataSource = self
self.observeMessages()
// Do any additional setup after loading the view.
}
@objc func back(_sender:UIBarButtonItem){
self.navigationController?.popToRootViewController(animated: true)
}
// func setupBubbleImages() { // let factory = JSQMessagesBubbleImageFactory() // outgoingBubbleImageView = factory?.outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue()) // incomingBubbleImageView = factory?.incomingMessagesBubbleImage(with:UIColor.jsq_messageBubbleLightGrey()) // } // // func setupAvatarImages() // { // collectionView!.collectioViewLayOut.incomingAvatarViewSize = CGsize.zero // collectionView!.collectioViewLayOut.outgoingAvatarViewSize = CGsize.zero // } //
} // Mark: - JSQmessagesviewcontroller Datasource
// extension ChatViewController // { // // override func collectionView( collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! // // // return jsqMessages[indexPath.item] // } // override func collectionView( collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int // { // return messages.Count // // // } // override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell // { // // let cell = super.collectionView(collectionView, cellForItemAt: indexPath) // as! JSQMessagesCollectionViewCell // // Let jsqMessage = jsqMessages[indexPath.item]
// if jsqMessage.senderID == self.senderID // { // cell?.textView?.textCollor = UIColor.white // // }else{ // // cell?.textView?.textColler = UIColor.black // // // } // return cell // } // // override func collectionView( collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource!{ // //// let jsqMessages = jsqMessages[indexPath.item] // if jsqMessage.senderId == self.senderId // { // return outgoingBubbleImageView // // }else { // // return incomingBubbleImageView // } // } // override func collectionView( collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! // { // return nil // // }
// Mark: send messages
extension ChatViewController { func PressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { if chat.messageIds.count == 0 { chat.save()
for account in chat.users {
account.save(new: chat)
}
}
let newMessage = Message(senderUID: currentUser.uid, senderDisplayName: currentUser.fullName, type: messagesRef.description() , text: text)
newMessage.save()
// chat.send(message: newMessage)//command shift k = clean the project
// JSQSystemSoundPlayer.jsq_playMessageSentSound() // // finishSendingMessage() }
}
// func add(_message:Message) // { // if Message.type == MessageType.text // { // let jsqMessage = JSQMessage(senderId: message.senderUID, displayName: message.senderDisplayName, text: message.text) // jsqMessages.append(jsqMessage) // } // // } func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { let name = message.sender.displayName return NSAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .caption1)])//1
}
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
return .bubble//2
}
// // } // // func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType { // // } // // func numberOfMessages(in messagesCollectionView: MessagesCollectionView) -> Int { // // } // // func heightForLocation(message: MessageType, at indexPath: IndexPath, with maxWidth: CGFloat, in messagesCollectionView: MessagesCollectionView) -> CGFloat { // // }
// MessagesDataSource // MessagesLayoutDelegate // MessagesDisplayDelegate
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
//
extension ChatViewController: MessagesDataSource { func currentSender() -> Sender { return currentSender() }
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messages[indexPath.section] as! MessageType
}
func numberOfMessages(in messagesCollectionView: MessagesCollectionView) -> Int {
return messages.count
}
//
}
func isFromCurrentSender(message: MessageType) -> Bool {
return true }
extension ChatViewController { func observeMessages() { let chatMessageIdsRef = chat.ref.child("messageIds") chatMessageIdsRef.observe(.childAdded, with: { snapshot in let messageId = snapshot.value as! String WADatabaseReference.messages.reference().child(messageId).observe(.value, with: { snapshot in let message = Message(dictionary: snapshot.value as! [String : Any]) self.messages.append(message) // self.add(message) // self.finishReceivingMessage() }) }) } }// This is what I want my project to look like.
This code allows me to see the new message view but does not allow me to see bubble chat and I am not able to send the text . Here is how my project looks with my code.
// // ContactsPickerViewController.swift // Moments1 // // Created // Copyright © . All rights reserved. //
import UIKit import Firebase import VENTokenField
class ContactsPickerViewController: UITableViewController {
struct StoryBoard {
static let contactCell = "ContactCell"
static let showChatViewController = "ShowChatViewController"
}
var chats:[Chat]! // chat is a property that someone will apss into us
var accounts = [User]()
var currentUser:User!
var selectedAccounts = [User]() // the one we choose
@IBOutlet weak var nextBarButtonItem: UIBarButtonItem!
@IBOutlet weak var contactsPickerField: VENTokenField!
override func viewDidLoad() {
super.viewDidLoad()
title = "New Message"
navigationItem.rightBarButtonItem = nextBarButtonItem
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window!.rootViewController as! UITabBarController
let firstNavVC = tabBarController.viewControllers!.first as! UINavigationController
let newsfeedTVC = firstNavVC.viewControllers.first as! NewsfeedTableViewController//good
//bad ...let newsfeedTVC = firstNavVC.topViewController as! NewsfeedTableViewController
currentUser = newsfeedTVC.currentUser
contactsPickerField.placeholderText = "Search...."
contactsPickerField.setColorScheme(UIColor.purple)// he made it red i made it uicoller.purple instead of red
contactsPickerField.delimiters = [",",";","--"]
contactsPickerField.toLabelTextColor = UIColor.black
contactsPickerField.dataSource = self
contactsPickerField.delegate = self
fetchUsers()
}
/////////////////////////***** fetch users code below and above **////////////// func fetchUsers() {
let accountsRef = WADatabaseReference.users(uid: currentUser.uid).reference().child("follows")
accountsRef.observe(.childAdded, with: {snapshot in
let user = User(dictionary:snapshot.value as! [String:Any])
self.accounts.insert(user, at: 0)
let indexPath = IndexPath(row:0,section:0)
self.tableView.insertRows(at: [indexPath], with: .fade)
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.accounts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StoryBoard.contactCell, for: indexPath) as! ContactTableViewCell
let user = accounts[indexPath.row]
cell.user = user
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ContactTableViewCell cell.added = !cell.added
if cell.added == true
{
self.addRecipient(account: cell.user)
}else {
let index = selectedAccounts.index(of: cell.user)!
self.deleteRecipient(account: cell.user, index: index)
}
}
func addRecipient(account:User)
{
self.selectedAccounts.append(account)
self.contactsPickerField.reloadData()// start new video 7 here
}
func deleteRecipient(account:User,index:Int )
{
selectedAccounts.remove(at: index)
self.contactsPickerField.reloadData()
}
@IBAction func nextDidTap()
{
var chatAccounts = selectedAccounts
chatAccounts.append(currentUser)
if let chat = findChat(among: chatAccounts)
{
self.performSegue(withIdentifier: StoryBoard.showChatViewController, sender: chat)
}else{
var title = ""
for acc in chatAccounts
{
if title == ""
{
title += "\(acc.fullName)"
}else{
title = ", \(acc.fullName)"
}
}
}
let newChat = Chat(users: chatAccounts, title: title!, featureImageUId: chatAccounts.first!.uid)
self.performSegue(withIdentifier: StoryBoard.showChatViewController, sender: newChat)
}
func findChat(among chatAccounts: [User]) -> Chat?
{
if chats == nil {
return nil
}
for chat in chats {
var results = [Bool]()
for acc in chatAccounts
{
let result = chat.users.contains(acc) //chat.users.contains(acc)
results.append(result)
}
if !results.contains(false)
{
return chat
}
}
return nil
}///////////*********/////////////
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == StoryBoard.showChatViewController
{
let chat = sender as! Chat
let chatVC = segue.destination as! ChatViewController///////
//chatVC.currentUser = //currentUser.uid /////*****chatVC.senderID from JSQmessages ViewController as stackoverflow///////////////4:37 video////
// need to create the identifier of the sender with messageKit
////is were deprecated begins***** *****//
// chatVC.senderDisplayName = currentUser.fullName///***///
chatVC.chat = chat
chatVC.currentUser = self.currentUser
chatVC.hidesBottomBarWhenPushed = true
}
}
}
extension ContactsPickerViewController: VENTokenFieldDataSource { func tokenField( tokenField: VENTokenField, titleForTokenAt index: UInt) -> String { return selectedAccounts[Int(index)].fullName } func numberOfTokens(in tokenField: VENTokenField) -> UInt { return UInt(selectedAccounts.count) } } extension ContactsPickerViewController:VENTokenFieldDelegate { func tokenField( tokenField: VENTokenField, didEnterText text: String) {
}
func tokenField(_ tokenField: VENTokenField, didDeleteTokenAt index: UInt) {
let indexPath = IndexPath(row:Int(index), section:0)
let cell = tableView.cellForRow(at: indexPath) as! ContactTableViewCell
cell.added = !cell.added
self.deleteRecipient(account: cell.user, index: Int(index))
}
}
This issue has been marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
This issue has been auto-closed because there hasn't been any activity for at least 21 days. However, we really appreciate your contribution, so thank you for that! 🙏 Also, feel free to open a new issue if you still experience this problem 👍.
@reginaagst I just completed one of my app conversion which earlier using JSQMessage library. Let me know if you need any help.