-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelsViewController
More file actions
241 lines (186 loc) · 6.78 KB
/
ChannelsViewController
File metadata and controls
241 lines (186 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
// ChannelsViewController.swift
// RentAdate
//
// Created by Kassandra Capretta on 2/2/20.
// Copyright © 2020 Kassandra Capretta. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseFirestore
class ChannelsViewController: UITableViewController {
private let toolbarLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 15)
return label
}()
private let channelCellIdentifier = "channelCell"
private var currentChannelAlertController: UIAlertController?
private let db = Firestore.firestore()
private var channelReference: CollectionReference {
return db.collection("channels")
}
private var channels = [Channel]()
private var channelListener: ListenerRegistration?
private let currentUser: User
deinit {
channelListener?.remove()
}
init(currentUser: User) {
self.currentUser = currentUser
super.init(style: .grouped)
title = "Channels"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
clearsSelectionOnViewWillAppear = true
tableView.register(UITableViewCell.self, forCellReuseIdentifier: channelCellIdentifier)
toolbarItems = [
UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(customView: toolbarLabel),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonPressed)),
]
toolbarLabel.text = AppSettings.displayName
channelListener = channelReference.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error listening for channel updates: \(error?.localizedDescription ?? "No error")")
return
}
snapshot.documentChanges.forEach { change in
self.handleDocumentChange(change)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.isToolbarHidden = true
}
// MARK: - Actions
@objc private func signOut() {
let ac = UIAlertController(title: nil, message: "Are you sure you want to sign out?", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
ac.addAction(UIAlertAction(title: "Sign Out", style: .destructive, handler: { _ in
do {
try Auth.auth().signOut()
} catch {
print("Error signing out: \(error.localizedDescription)")
}
}))
present(ac, animated: true, completion: nil)
}
@objc private func addButtonPressed() {
let ac = UIAlertController(title: "Create a new Channel", message: nil, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
ac.addTextField { field in
field.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
field.enablesReturnKeyAutomatically = true
field.autocapitalizationType = .words
field.clearButtonMode = .whileEditing
field.placeholder = "Channel name"
field.returnKeyType = .done
field.tintColor = .primary
}
let createAction = UIAlertAction(title: "Create", style: .default, handler: { _ in
self.createChannel()
})
createAction.isEnabled = false
ac.addAction(createAction)
ac.preferredAction = createAction
present(ac, animated: true) {
ac.textFields?.first?.becomeFirstResponder()
}
currentChannelAlertController = ac
}
@objc private func textFieldDidChange(_ field: UITextField) {
guard let ac = currentChannelAlertController else {
return
}
ac.preferredAction?.isEnabled = field.hasText
}
// MARK: - Helpers
private func createChannel() {
guard let ac = currentChannelAlertController else {
return
}
guard let channelName = ac.textFields?.first?.text else {
return
}
let channel = Channel(name: channelName)
channelReference.addDocument(data: channel.representation) { error in
if let e = error {
print("Error saving channel: \(e.localizedDescription)")
}
}
}
private func addChannelToTable(_ channel: Channel) {
guard !channels.contains(channel) else {
return
}
channels.append(channel)
channels.sort()
guard let index = channels.index(of: channel) else {
return
}
tableView.insertRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
private func updateChannelInTable(_ channel: Channel) {
guard let index = channels.index(of: channel) else {
return
}
channels[index] = channel
tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
private func removeChannelFromTable(_ channel: Channel) {
guard let index = channels.index(of: channel) else {
return
}
channels.remove(at: index)
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
private func handleDocumentChange(_ change: DocumentChange) {
guard let channel = Channel(document: change.document) else {
return
}
switch change.type {
case .added:
addChannelToTable(channel)
case .modified:
updateChannelInTable(channel)
case .removed:
removeChannelFromTable(channel)
}
}
}
// MARK: - TableViewDelegate
extension ChannelsViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return channels.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: channelCellIdentifier, for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = channels[indexPath.row].name
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let channel = channels[indexPath.row]
let vc = ChatViewController(user: currentUser, channel: channel)
navigationController?.pushViewController(vc, animated: true)
}
}