1

因此,我試圖在正在構建的應用程序中實現一對一聊天系統,並且遇到了一些麻煩。這是我迄今爲止。Firebase&JSQMessagesViewController Ios Swift 2中的一對一聊天

這是我的代碼

請幫助我,我也非常感謝任何例子。謝謝

`

import UIKit 
import JSQMessagesViewController 
import Firebase 

class MessagesViewController: JSQMessagesViewController { 


    var messages = [Message]() 
    var userImage = "" 
    var toUser: String! 
    var toUserImageUrl: String! 
    var avatars = Dictionary<String, UIImage>() 
    var outgoingBubbleImageView: JSQMessagesBubbleImage! 
    var incomingBubbleImageView: JSQMessagesBubbleImage! 
    var senderImageUrl: String! 
    var batchMessages = true 
// var ref: Firebase! 

    // *** STEP 1: STORE FIREBASE REFERENCES 
    var messagesRef: FIRDatabaseReference! 

    private func setupBubbles() { 
     let factory = JSQMessagesBubbleImageFactory() 
     outgoingBubbleImageView = factory.outgoingMessagesBubbleImageWithColor(
      UIColor.jsq_messageBubbleBlueColor()) 
     incomingBubbleImageView = factory.incomingMessagesBubbleImageWithColor(
      UIColor.jsq_messageBubbleLightGrayColor()) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

print(toUser) 

     inputToolbar.contentView.leftBarButtonItem = nil 
     automaticallyScrollsToMostRecentMessage = true 
     // self.collectionView.backgroundColor = UIColor.blackColor() 
     self.navigationItem.hidesBackButton = true 
     let newBackButton = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.Bordered, target: self, action: #selector(MessagesViewController.back(_:))) 
     self.navigationItem.leftBarButtonItem = newBackButton; 
     self.navigationController?.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor() 

     senderId = (senderId != nil) ? senderId : "Anonymous" 
     if let urlString = userImage as? NSString { 
      setupAvatarImage(senderId, imageUrl: senderImageUrl, incoming: false) 
      senderImageUrl = urlString as String 
     } else { 
      setupAvatarColor(senderDisplayName, incoming: false) 
      senderImageUrl = "" 
     } 

     senderId = Constants.currentUser 

     self.title = toUser 

     // No avatars 
     collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSizeZero 
     collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSizeZero 

     setupBubbles() 
     setupFirebase() 
    } 

    func back(sender: UIBarButtonItem) { 
     self.dismissViewControllerAnimated(true, completion: nil) 
    } 

    func setupFirebase() { 
     // *** STEP 2: SETUP FIREBASE 
     messagesRef = FIRDatabase.database().reference() 

     // *** STEP 4: RECEIVE MESSAGES FROM FIREBASE (limited to latest 25 messages) 

     messagesRef.observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in 
         let text = snapshot.value!["text"] as? String 
         let sender = snapshot.value!["from"] as? String 
         let toUsername = snapshot.value!["toUser"] as? String 
         let senderimageUrl = snapshot.value!["senderimageUrl"] as? String 
         let toUserImageUrl = snapshot.value!["toUserimageUrl"] as? String 

         let message = Message(text: text, sender: sender, toUsername: toUsername, senderimageUrl: senderimageUrl, toUserimageUrl: toUserImageUrl) 
         self.messages.append(message) 
         self.finishReceivingMessage() 
     }) 

    } 

    func sendMessage(text: String!, sender: String!, to: String!) { 
     // *** STEP 3: ADD A MESSAGE TO FIREBASE 


     messagesRef.childByAutoId().setValue([ 
      "text":text, 
      "toUser":toUser, 
      "from":self.senderId, 
      "senderimageUrl":senderImageUrl, 
      "toUserimageUrl":toUserImageUrl 
      ]) 
    } 

    func tempSendMessage(text: String!, sender: String!, to: String!) { 
     let message = Message(text: text, sender: sender, toUsername: to, senderimageUrl: senderImageUrl, toUserimageUrl: toUserImageUrl) 
     messages.append(message) 
    } 


    func setupAvatarImage(name: String, imageUrl: String?, incoming: Bool) { 
     if let stringUrl = imageUrl { 
      if let url = NSURL(string: stringUrl) { 
       if let data = NSData(contentsOfURL: url) { 
        let image = UIImage(data: data) 
        let diameter = incoming ? UInt(collectionView.collectionViewLayout.incomingAvatarViewSize.width) : UInt(collectionView.collectionViewLayout.outgoingAvatarViewSize.width) 
        let avatarImage = JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: diameter).avatarImage 
        avatars[name] = avatarImage 
        return 
       } 
      } 
     } 

     // At some point, we failed at getting the image (probably broken URL), so default to avatarColor 
     setupAvatarColor(name, incoming: incoming) 
    } 

    func setupAvatarColor(name: String, incoming: Bool) { 
     let diameter = incoming ? UInt(collectionView.collectionViewLayout.incomingAvatarViewSize.width) : UInt(collectionView.collectionViewLayout.outgoingAvatarViewSize.width) 

     let rgbValue = name.hash 
     let r = CGFloat(Float((rgbValue & 0xFF0000) >> 16)/255.0) 
     let g = CGFloat(Float((rgbValue & 0xFF00) >> 8)/255.0) 
     let b = CGFloat(Float(rgbValue & 0xFF)/255.0) 
     let color = UIColor(red: r, green: g, blue: b, alpha: 0.5) 

     let nameLength = name.characters.count 
     let initials : String? = name.substringToIndex(toUser.startIndex.advancedBy(min(3, nameLength))) 
     let userImage = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials(initials, backgroundColor: color, textColor: UIColor.blackColor(), font: UIFont.systemFontOfSize(CGFloat(13)), diameter: diameter).avatarImage 

     avatars[name] = userImage 
    } 

    override func viewDidAppear(animated: Bool) { 
     super.viewDidAppear(animated) 
     collectionView.collectionViewLayout.springinessEnabled = true 
    } 

    override func viewWillDisappear(animated: Bool) { 
     super.viewWillDisappear(animated) 

//  if ref != nil { 
//   ref.unauth() 
//  } 
    } 

    // ACTIONS 

    func receivedMessagePressed(sender: UIBarButtonItem) { 
     // Simulate reciving message 
     showTypingIndicator = !showTypingIndicator 
     scrollToBottomAnimated(true) 
    } 

    override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!){ 
     JSQSystemSoundPlayer.jsq_playMessageSentSound() 

     sendMessage(text, sender: senderId, to: toUser) 

     finishSendingMessage() 
    } 

    override func didPressAccessoryButton(sender: UIButton!) { 
     print("Camera pressed!") 
    } 


    override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! { 
     return messages[indexPath.item] 
    } 

    override func collectionView(collectionView: JSQMessagesCollectionView!, 
           messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! { 
     let message = messages[indexPath.item] // 1 
     if message.senderId() == self.senderId{ // 2 
      return outgoingBubbleImageView 
     } else { // 3 
      return incomingBubbleImageView 
     } 
    } 

    override func collectionView(collectionView: JSQMessagesCollectionView!, 
           avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! { 
     return nil 
    } 

    func collectionView(collectionView: JSQMessagesCollectionView!, bubbleImageViewForItemAtIndexPath indexPath: NSIndexPath!) -> UIImageView! { 
     let message = messages[indexPath.item] 

     if message.senderId() == self.senderId { 
      return UIImageView(image: outgoingBubbleImageView.messageBubbleImage, highlightedImage: outgoingBubbleImageView.messageBubbleHighlightedImage) 
     } 

     return UIImageView(image: incomingBubbleImageView.messageBubbleImage, highlightedImage: incomingBubbleImageView.messageBubbleHighlightedImage) 
    } 

    func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageViewForItemAtIndexPath indexPath: NSIndexPath!) -> UIImageView! { 
     let message = messages[indexPath.item] 
     if let avatar = avatars[message.senderId()] { 
      return UIImageView(image: avatar) 
     } else { 
      setupAvatarImage(message.senderId(), imageUrl: message.senderimageUrl(), incoming: true) 
      return UIImageView(image:avatars[message.senderId()]) 
     } 
    } 

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return messages.count 
    } 


    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
     let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell 

     let message = messages[indexPath.item] 
     if message.senderId() == self.senderId { 
      cell.textView.textColor = UIColor.whiteColor() 
     } else { 
      cell.textView.textColor = UIColor.blackColor() 
     } 

     let attributes : [String:AnyObject] = [NSForegroundColorAttributeName:cell.textView.textColor!, NSUnderlineStyleAttributeName: 1] 
     cell.textView.linkTextAttributes = attributes 

     //  cell.textView.linkTextAttributes = [NSForegroundColorAttributeName: cell.textView.textColor, 
     //   NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle] 
     return cell 
    } 


    // View usernames above bubbles 
    override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { 
     let message = messages[indexPath.item]; 

     // Sent by me, skip 
     if message.senderId() == self.senderId { 
      return nil; 
     } 

     // Same as previous sender, skip 
     if indexPath.item > 0 { 
      let previousMessage = messages[indexPath.item - 1]; 
      if previousMessage.senderId() == message.senderId() { 
       return nil; 
      } 
     } 

     return NSAttributedString(string:message.senderId()) 
    } 

    override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { 
     let message = messages[indexPath.item] 

     // Sent by me, skip 
     if message.senderId() == self.senderId { 
      return CGFloat(0.0); 
     } 

     // Same as previous sender, skip 
     if indexPath.item > 0 { 
      let previousMessage = messages[indexPath.item - 1]; 
      if previousMessage.senderId() == message.senderId() { 
       return CGFloat(0.0); 
      } 
     } 

     return kJSQMessagesCollectionViewCellLabelHeightDefault 
    } 



} 

`

+0

我根本沒有看到任何問題。這裏只是一個毛毯,我的代碼示例會很好。我錯過了什麼?什麼不起作用,我們怎麼幫忙,你有什麼問題? –

+0

好吧,所以基本上我試圖讓一個私人聊天系統像whatsapp或Facebook的使者,但我很難找出如何做到這一點 –

+0

雅所以你有什麼麻煩。是不是像你期望的那樣工作。你不知道下一步是什麼? –

回答

0

所以我建議檢查出

Swift Example can be found in the SwiftExample folder just open the SwiftExample.xcworkspace.

https://github.com/jessesquires/JSQMessagesViewController

是分開JSQMessagesViewController的,目前維持。也有一個組和1對話的例子。這應該有助於你完成私人對話。但我認爲你錯過了一個關鍵組件,那就是你的對話視圖。那就是你開始談話的地方。然後,您應該在您的Firebase後端擁有一個終端,以便您可以點擊用戶以前的所有對話。這樣他們可以再次打開它們。