新增聊天室
到此為止的原始碼# 新增聊天室
打開 RoomListViewController.swift
加入下列 import
import SVProgressHUD
import FirebaseDatabase
在 viewDidLoad 上方加入
// 聊天室名稱欄位
var roomNameField: UITextField!
// 聊天室建立按鈕
var createRoomButton: UIButton!
編輯 viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "房間列表"
setupUI()
}
並新增下列 func
func setupUI() {
// 灰色底色的容器
let bar = UIView()
bar.translatesAutoresizingMaskIntoConstraints = false
bar.backgroundColor = UIColor.lightGray
view.addSubview(bar)
bar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
bar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
bar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
roomNameField = UITextField()
roomNameField.placeholder = "輸入房間名稱"
roomNameField.autocapitalizationType = .none
roomNameField.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.7)
createRoomButton = UIButton(type: .system)
createRoomButton.setTitle("新增", for: .normal)
createRoomButton.addTarget(self, action: #selector(createRoom(_:)), for: .touchUpInside)
// 使用StackView簡化排版
let container = UIStackView(arrangedSubviews: [roomNameField, createRoomButton])
container.translatesAutoresizingMaskIntoConstraints = false
container.alignment = .center
container.axis = .horizontal
container.spacing = 4
bar.addSubview(container)
container.bottomAnchor.constraint(equalTo: bar.bottomAnchor, constant: -4).isActive = true
container.leftAnchor.constraint(equalTo: bar.leftAnchor, constant: 4).isActive = true
container.rightAnchor.constraint(equalTo: bar.rightAnchor, constant: -4).isActive = true
container.topAnchor.constraint(equalTo: bar.topAnchor, constant: 4).isActive = true
}
func createRoom(_ sender: Any) {
// TODO: 稍後實作
}
在 viewDidLoad 上方加入
// 存取資料庫用參考
var ref: FIRDatabaseReference!
編輯 viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "房間列表"
setupUI()
// 存取聊天室房間資料庫用參考
roomsRef = FIRDatabase.database().reference().child("rooms")
}
接著實作 func createRoom
func createRoom(_ sender: Any) {
// 如果 roomName 沒有填寫就不繼續
guard let roomName = roomNameField.text, !roomName.isEmpty else {
return
}
// 建立一個 Room
// 結構為
// RoomID - 自動產生
// |-- RoomData - 下面setValue的對象
let newRoom = roomsRef.childByAutoId()
// 建立一個 Room
// 結構為
// RoomID - 自動產生
// |-- RoomData - 下面setValue的對象
let newRoom = roomsRef.childByAutoId()
newRoom.setValue(["name": roomName]) {[unowned self] (error, _) in
if let error = error {
print(error)
}
// 清除房間名稱欄位
self.roomNameField.text = nil
}
}
運行APP並試著新增一兩個聊天室,一邊觀察Firebase Console中的Database是否產生變化,如果正確運行的話可以得到與下列類似的結果