Skip to content

Instantly share code, notes, and snippets.

@cardoso

cardoso/ChatView.swift Secret

Last active May 18, 2020
Embed
What would you like to do?
import SwiftUI
import StreamChatClient
struct ChatView: View {
let channel = Client.shared.channel(type: .messaging, id: "general")
@State
var text: String = ""
@State
var messages: [Message] = []
var body: some View {
VStack {
List(messages.reversed(), id: \.self) {
Text("\($0.user.id): \($0.text)")
.scaleEffect(x: 1, y: -1, anchor: .center)
}
.scaleEffect(x: 1, y: -1, anchor: .center)
.offset(x: 0, y: 2)
HStack {
TextField("Type a message", text: $text)
Button(action: self.send) {
Text("Send")
}
}.padding()
}
.navigationBarTitle("General")
.onAppear(perform: onAppear)
}
func send() {
channel.send(message: .init(text: text)) {
switch $0 {
case .success(let response):
print(response)
self.text = ""
case .failure(let error):
print(error)
}
}
}
func onAppear() {
channel.watch(options: [.all]) {
switch $0 {
case .success(let response):
self.messages += response.messages
case .failure(let error):
break
}
}
channel.subscribe(forEvents: [.messageNew]) {
switch $0 {
case .messageNew(let message, _, _, _):
self.messages += [message]
default:
break
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.