進入聊天室

首先安裝聊天畫面所需要的套件,打開Pods > Podfile

將內容更改為

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'LetsChat' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for LetsChat
  pod 'Firebase/Core'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'Firebase/Storage'
  pod 'Firebase/Database'
  pod 'SVProgressHUD'
  pod 'IQKeyboardManagerSwift'
  pod 'JSQMessagesViewController', :git => 'https://github.com/jessesquires/JSQMessagesViewController.git', :branch => 'develop'
end

安裝Cocoapods章節相同,在Terminal中切換至專案目錄,運行

pod install

安裝完成後回到Xcode,進行一次Build

接著回到LetsChat > LetsChat(名稱依專案而異)

新增一個Cocoa Touch Class命名為ChatViewController,Subclass of: UIViewController,不勾選Also create XIB file

新增importChatViewController.swift

import JSQMessagesViewController
import FirebaseDatabase
import FirebaseAuth

並將父類別改為JSQMessagesViewController,如下

class ChatViewController: JSQMessagesViewController {

func viewDidLoad()上方加入

    // 房間ID用來讀取該房間的訊息
    var roomID: String!
    // 房間名稱
    var roomName: String!
    // 訊息資料
    var messages = [[String: String]]()
    // 訊息記錄節點
    var messageRef: FIRDatabaseReference!

改寫func viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        messageRef = FIRDatabase.database().reference().child("messages/\(roomID!)")
    }

回到RoomListViewController.swiftextension中追加實作下列程式

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let roomData = rooms[indexPath.row]

        // 必須取得id 和name 才繼續進行
        guard let roomID = roomData["id"], let roomName = roomData["name"] else {
            return
        }

        let vc = ChatViewController()
        vc.roomID = roomID
        vc.roomName = roomName

        navigationController?.pushViewController(vc, animated: true)
    }

運行APP,並點選房間名稱,即切換到聊天畫面

程式碼下載

results matching ""

    No results matching ""