根据时间戳显示消息(已发送和已接收)

时间:2018-06-21 01:46:27

标签: ios swift firebase google-cloud-firestore

我已经为此苦苦挣扎了几天,我真的需要您的帮助。 当前,已发送的消息首先显示,根据其时间戳全部显示在视图控制器的左侧,然后再将接收到的消息显示在视图控制器的右侧。但是,我希望发送和接收的消息都根据时间戳进行排序,以使其类似于真实世界。例如,约翰在上午9:30向彼得发送消息“嗨”,彼得在上午10点答复“我很好”,约翰在10:15向彼得发送消息说“很好听”。发送的消息首先显示在左侧,而接收的消息则显示在右侧,但是我希望它反映真实的世界(接收和发送的时间戳)。

    override func viewDidLoad() {
    super.viewDidLoad()
    loadPosts()
    loadPostsReceivedMessage()
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ChatCollectionViewCell    
     let senderIDNumber = Auth.auth().currentUser?.uid

       //Setup the messageReceived and messageSent
        if chats[indexPath.row].senderID == senderIDNumber {
        if let chatsText = chats[indexPath.row].message{
            let size = CGSize(width: 250, height: 1000)
            let options = 
      NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
            cell.messageSend.frame = CGRect(x:8,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
            cell.textBubbleView.frame = CGRect(x:0,y:0,width:estimatedFrame.width + 16 + 8, height:estimatedFrame.height + 20)
         //showOutgoingMessage(text: chats[indexPath.row].message)
    }
            cell.messageSend.text = chats[indexPath.row].message
        }
    else {
            cell.messageReceived.text = chats[indexPath.row].message
            let chatsText = chats[indexPath.row].message
            let size = CGSize(width: 250, height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let estimatedFrame = NSString(string: chatsText!).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
            cell.messageReceived.frame = CGRect(x:view.frame.width - estimatedFrame.width - 30,y:0,width:estimatedFrame.width + 16, height:estimatedFrame.height + 20)
            cell.textBubbleView.frame = CGRect(x:view.frame.width - estimatedFrame.width - 30,y:0,width:estimatedFrame.width + 16 + 4, height:estimatedFrame.height + 20)
    }
    return cell
}

    func collectionView(_ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath) -> CGSize {
     if let chatsText = chats[indexPath.row].message {
    let size = CGSize(width: 250, height: 1000)
        let options = 
      NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrame = NSString(string: chatsText).boundingRect(with: 
        size, options: options, attributes: [NSAttributedStringKey.font : 
        UIFont.systemFont(ofSize: 18)], context: nil)
        return CGSize(width: view.frame.width, height: estimatedFrame.height + 
            20)
          }

    return CGSize(width: view.frame.width, height: 200)
      }

      //Get Message sent
     func loadPosts() {
    let senderIDNumber = Auth.auth().currentUser?.uid
    let chatsRef = db.collection("chats").order(by: "timestamp", descending: false)
    chatsRef.whereField("senderID", isEqualTo: senderIDNumber!).whereField("receiverID", isEqualTo: receiverIDNumber)
        .addSnapshotListener { querySnapshot, error in
            guard let documents = querySnapshot?.documents else {
                print("Error fetching documents: \(error!)")
                return
            }
            for document in documents {
                let messageText = document.data()["message"] as? String
                let senderIDNumber = document.data()["senderID"] as? String
                let receiverIDNumber = document.data()["receiverID"] as? String
                let timestamp = document.data()["timestamp"] as? String
                guard let sender = document.data()["sender"] as? String else {return}
               // let conversationsCounter = document.data()["conversationsCounter"] as? Int
                guard let profileUrl = document.data()["profileUrl"] as? String else { return}
                let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!, profileImageUrl: profileUrl, senderString: sender)
self.chats.append(chat)
print(self.chats)
self.collectionView.reloadData()
}
}
}


//Get message received

     func loadPostsReceivedMessage() {
    /* let uid = Auth.auth().currentUser?.uid
     let ref = Database.database().reference()
     ref.child("users").child(uid!).observeSingleEvent(of: .value, with: { 
     (snapshot) in
        if let dic = snapshot.value as? [String: AnyObject]{
            let currentUser = dic["username"] as? String
            let senderIDNumber = Auth.auth().currentUser?.uid
        } */
            let chatsRef = db.collection("chats").order(by: "timestamp", 
         descending: false)
            print("thecurrentreceiver"+senderString)
            print("thecurrentsender"+receiverIDNumber)
         chatsRef.whereField("receiverID", isEqualTo: 
        senderString).whereField("sender", isEqualTo: receiverIDNumber)
                .addSnapshotListener { querySnapshot, error in
                    guard let documents = querySnapshot?.documents else {
                        print("Error fetching documents: \(error!)")
                        return
                    }
                    for document in documents {
                        let messageText = document.data()["message"] as? String
                        let senderIDNumber = document.data()["senderID"] as? 
              String
                        let receiverIDNumber = document.data()["receiverID"] as? 
           String
                        let timestamp = document.data()["timestamp"] as? String
                        // let conversationsCounter = document.data() 
       ["conversationsCounter"] as? Int
                        guard let profileUrl = document.data()["profileUrl"] as? String else { return}
                        guard let sender = document.data()["sender"] as? String else {return}
                        let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!,profileImageUrl: profileUrl, senderString: sender)
                        print("whatisthemessage"+messageText!)
                        self.chats.append(chat)
                        print(self.chats)
                        self.collectionView.reloadData()
                    }
            }
}

1 个答案:

答案 0 :(得分:0)

在loadPostsReceivedMessage()方法的最后添加以下行:

async function doSomething () {
  const someApiRes = await callSomeApi()
  console.log('I will be displayed before someApiRes is finished.')
  console.log(`someApiRes will be undefined: ${someApiRes}`)
}

这将对您的数据进行排序。如果所有聊天都向后,请将>更改为<< / p>

如果这不起作用,请转到here了解如何将字符串转换为日期。