发送消息在JSQMessageViewController

时间:2015-12-24 07:03:54

标签: ios iphone xcode swift parse-platform

我正在使用JSQMessageviewcontroller来使用parse创建聊天cliet。除了“我发送的消息在jsqmessage数组中被添加两次”之外,我在实现所有目标方面都非常成功。 Althuogh我已经检查过JSQMessage数组是否已经包含该消息,不应该添加它,但是在发送消息的情况下条件为false。

这是我的代码:

import UIKit
import JSQMessagesViewController
import Parse

class MessageViewController: JSQMessagesViewController {

var chatWith : String?
var chattingWith = false
let incomingBubble = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImageWithColor(UIColor(red: 10/255, green: 180/255, blue: 230/255, alpha: 1.0))
let outgoingBubble = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImageWithColor(UIColor.lightGrayColor())
var messages = [JSQMessage]()
var updateTimer = NSTimer()
let updateDelay = 2.0
var jsqMessages : [JSQMessage] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.setup()

    updateTimer = NSTimer.scheduledTimerWithTimeInterval(updateDelay, target: self, selector: "update", userInfo: nil, repeats: true)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidDisappear(animated: Bool) {

    updateTimer.invalidate()

}
func reloadMessagesView() {
    self.collectionView?.reloadData()
 }
 }

//MARK - Setup
extension MessageViewController {


func setup() {
    self.senderId = PFUser.currentUser()?.objectId!
    self.senderDisplayName = PFUser.currentUser()?.username!

}
}

//MARK - Data Source
extension MessageViewController {

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

override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
    let data = self.messages[indexPath.row]
    return data
}

override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) {
    self.messages.removeAtIndex(indexPath.row)
}

override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
    let data = messages[indexPath.row]
    switch(data.senderId) {
    case self.senderId:
        return self.outgoingBubble
    default:
        return self.incomingBubble
     }
}

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

//MARK - Toolbar
extension MessageViewController {
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
    let message = JSQMessage(senderId: PFUser.currentUser()?.objectId!, senderDisplayName: PFUser.currentUser()?.username!, date: date, text: text)
    print("sent messages = \(message)")
    if !self.messages.contains(message) {
       self.messages += [message]
    }

    self.sendMessageToParse(message , date: date)
    self.finishSendingMessage()
 }

override func didPressAccessoryButton(sender: UIButton!) {

}


}

//MARK - Syncano
extension MessageViewController {

func sendMessageToParse(message: JSQMessage , date : NSDate) {

    let obj = PFObject(className: "Chat")
    obj.setObject((PFUser.currentUser()?.username)!, forKey: "username")
    obj.setObject(message.text!, forKey: "Text")
    obj.setObject(chatWith!, forKey: "To")
    obj.setObject(PFUser.currentUser()!, forKey: "user")
    obj.setObject(date, forKey: "dateCreatedOn")
    try! obj.save()


 }

func update() {
    let query = PFQuery(className: "Chat")
    query.limit = 10
    query.includeKey("user")
//        query.whereKey("To", equalTo: chatWith!)
    query.findObjectsInBackgroundWithBlock {
        (results: [PFObject]?, error: NSError?) -> Void in

        for i in results! {

            if i.objectForKey("username") as? String == PFUser.currentUser()?.username! {

                let message = self.jsqMessageFromParseMessage(i, senderId: (PFUser.currentUser()?.objectId!)!, senderDisplayName: i.objectForKey("username")! as! String)
                print("received message : \(message)")
                self.jsqMessageArray(message)
            }else {

                let message = self.jsqMessageFromParseMessage(i, senderId: i.objectForKey("To")! as! String, senderDisplayName: i.objectForKey("To")! as! String)
                self.jsqMessageArray(message)
            }

        }


    }

 }



 func jsqMessageFromParseMessage(message: PFObject , senderId : String , senderDisplayName : String) -> JSQMessage {
    let jsqMessage = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: message["dateCreatedOn"] as! NSDate, text: message["Text"] as! String)
    return jsqMessage
}

func jsqMessageArray(jsqmessage : JSQMessage){

    if self.messages.contains(jsqmessage) {

    }else {
        //
        self.messages.append(jsqmessage)
        self.finishReceivingMessage()
        self.reloadMessagesView()

    }

}
}

如果有人能提供帮助,我们将非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

有一种方法可以在名为messageHash的JSQMessageData协议上实现。它返回一个Int,它意味着每个消息的唯一ID。您应该能够使用它来检查并查看消息是否相同。

您需要创建一个符合JSQMessageData协议而不是使用JSQMessage的对象数据类

  class Message: JSQMessageData {

       func senderId()-> String {
          return //the result of currentUser()?.objectId
       }

      func senderDisplayName()-> String {
         return //the result of currentUser()?.username!
      }

      func date()-> NSDate {
         return // date
      }

      func isMediaMessage() -> Bool {
         return false
      }

      func messageHash()-> String {
         return //return a uniquely created id
      }

      func text()-> String {
         return // text
      }

  }

你应该可以在PFUser上做到这一点,虽然我不熟悉Parse告诉你这是否可能,但你真的只是将现有的属性重新映射为新名称所以它不应该'是个问题