iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
自我挑戰組

來寫看看app好了! Swift探索之旅系列 第 29

Day#29 對話(2)

前言

前一天終於把bug都修好,讓模擬器可以順利地打開喔。今天繼續把想要的主要功能做出來。

ConversationViewController

首先,我們把原本mock的資料換成從開新對話的對象,也就是方法didTapComposeButton中的result

使用guard確保資料有拿到,然後帶入新的view controller。此時在這邊除了拿名字作為聊天室的標題外,也確定為db key的email欄位有值。

private func createNewConversation(result: [String:String]) {
    guard let name = result["name"], let email = result["email"] else { 
        return
    }
    let vc = ChatViewController()
    vc.title = name
    vc.navigationItem.largeTitleDisplayMode = .never
    navigationController?.pushViewController(vc, animated: true)
}

ChatViewController

接下來畫面進入到chat view controller,因此我們來新增當中需要的內容。最終目標,我們希望可以可以送出訊息以及其他各種形式的對話。

首先,引入相關的函式庫。

import InputBarAccessoryView

ChatViewController

然後新增2個變數,otehrUserEmail是從剛剛createNewConversation拿到的email,我們作為辨識在跟誰聊天的key值。
isNewConversation將會被用於,如果這是一個新的對話,就要新增到db,然後顯示在conversation的table view中,若值為false的話,則會append在原本conversation中。

public let otherUserEmail: String
public var isNewConversation = false

針對新增的property,我們新增上必須的initializer。

init(with email: String) {
    self.otherUserEmail = email
    super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

接著把input bar的delegate指定給自己。並接著新增相對應的extension。

messageInputBar.delegate = self

我們首先確定傳出去的訊息不為空白值,使用trim進行檢查。
此時debug用,先print訊息確定真的內容有被抓取到、並顯示在console。

extension ChatViewController: InputBarAccessoryViewDelegate {
    func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
        guard !text.replacingOccurrences(of: " ", with: "").isEmpty else {
            return
        }
        
        print("Sending: \(text)")
        // send messages
        if isNewConversation {
            // add a new conversation to database
        } else {
            // append to existing conversation
        }
    }
}

當view成功跳轉並顯示後,我們再加上把滑鼠指針初始到打字區。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    messageInputBar.inputTextView.becomeFirstResponder()
}

DatabaseManager

chat的框架已經差不多寫好後,我們就可以針對後端資料庫的邏輯來建立方法。一樣先把框架寫出來~


// MARK: - Sending messages, conversations
extension DatabaseManager {
    
    /// Create a new conversation with target user email and first message sent
    public func createNewConversation(with otherUserEmail: String, firstMessage: Message, completion: (Bool)) {
        
    }
    
    /// fetch and return all the conversation for the user and passed in emaill
    public func getAllConversations(for email: String, completion: @escaping (Result<String, Error>) -> Void) {
        
    }
    
    /// Get all messages for a given conversation
    public func getAllMessagesForConversation(with id: String, completion: @escaping (Result<String, Error>) -> Void) {
        
    }
    
    /// Send message with target conversation and messages
    public func sendMessage(to conversation: String, message: Message, completion: @escaping (Bool) -> Void) {
        
    }
}

結語

今天雖然寫不少,但主要都是針對接下來的邏輯在寫框架,還沒實際走到開發。不知道鐵人賽是30天還是31天啊XD 希望明天跟後天可以把功能完成!

若上述內容有誤或可以改進的部分,歡迎留言以及提出任何指教~
謝謝 ヘ| ´ω` |ノ


上一篇
Day#28 上傳照片(2)+Debug
下一篇
Day#30 行百里者半九十
系列文
來寫看看app好了! Swift探索之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言