-
-
Notifications
You must be signed in to change notification settings - Fork 9
Tutorials
In this tutorial, you’ll learn how to implement a user interface for a chat features.
Completed sample is listed on this repository under the main branch.
This tutorials was built using:
- Xcode14
- iOS 16
Note that this tutorial assume a basic knowledge of SwiftUI. That said, let’s get started!
You can import ChatUI via Swift Package Manager or by using Sources in GitHub repository.
For this tutorial, I chose Swift Package Manager for my installation.
-
In Xcode, select File > Swift Packages > Add Package Dependency.
-
In the search bar, paste the ChatUI URL: https://github.com/jaesung-0o0/ChatUI
-
Select the branch as main to install.
-
Click Next, and then click Finish.
-
Import ChatUI
import ChatUI
struct User: UserProtocol {
var id { UUID().uuidString }
struct Message: MessageProtocol {
var id: String
var sender: User
var sentAt: Double
var editedAt: Double?
var readReceipt: ReadReceipt
var style: MessageStyle
}
struct Channel: ChannelProtocol {
var id: String
var name: String
var imageURL: URL?
var members: [User]
var createdAt: Double
var lastMessage: Message?
}
@StateObject private var configuration = ChatConfiguration(userID: "{USER.ID}")
ChatView()
.enviromentObject(configuration)
MessageList(messages) { message in
MessageRow(message: message)
}
.enviromentObject(configuration)
let appearance = Appearance(tint: {APP.MAIN.COLOR})
ChatView()
.enviroment(\.appearance, appearance)
When you want to access colors or fonts in Appearance
, use @Enviroment(\.appearance)
@Environment(\.appearance) var appearance
var body: some View {
Text("Start a New Chat")
.font(appearance.title)
.foregroundColor(appearance.tint)
}
Here is essential properties and functions used in the data model for ChatUI
import ChatUI
import SwiftUI
class ChatModel: ObservableObject {
let channel: Channel
@Published var messages: [Message]
func sendMessage(forStyle style: MessageStyle) {
let sendingMessage = Message(..., style: style, ...)
messages.insert(sendingMessage, at: 0)
// Send message by using chat SDK
YourChatSDK.sendMessage(...) {
// handle error / receipt status
}
}
}
ChannelStack(dataModel.channel) {
// Implement Step 6 here.
// Implement Step 7 here.
}
ChannelStack
provides ChannelInfoView
automatically based on the given channel object. To customize the ChannelInfoView
or layouts among the views in ChannelStack
such as MessageList
or MessageField
, please use VStack
and ToolbarItem
instead.
VStack(spacing: 0) {
// Implement Step 6 here.
// Implement Step 7 here.
}
.toolbar {
// Channel Info View
ToolbarItem(placement: .navigationLeading) {
ChannelInfoView(
title: dataModel.channel.name,
subtitle: "This is Q&A channel. Feel free to ask and answer",
imageURL: {SOME.URL}
)
}
}
MessageList(dataModel.messages) { message in
MessageRow(message: message)
}
MessageField { messageStyle in
dataModel.sendMessage(forStyle: messageStyle)
}