Messages
Sending messages in Threads.
Info
Message data
, publicMeta
and privateMeta
fields support any kind of data formats encoded to byte arrays. Examples in this section use JSON format serialization which is available directly in Swift.
Messages inside Threads
Messages inside Threads are sent in binary format. Before sending a message, you need to decide on the message format and choose the appropriate data serialization method.
For more information about the Threads architecture and best practices for sending messages, visit the Threads Documentation.
Sending Messages
Example of sending a message in Plain Text:
var threadID = "THREAD_ID"
guard let privMXEndpoint = endpointContainer..getEndpoint() else {return}
guard let messageData = "Message text".data(using: .utf8) else {return}
let messageID = try? privMXEndpoint.threadApi?
.sendMessage(in: threadID,
withPublicMeta: Data(),
withPrivateMeta: Data(),
containing: messageData)
Getting Messages
Define message item struct with decoded data
and publicMeta
. This time we use some decoding of Data fields and mapping generic message to struct used within developed App:
struct MessagePublicMeta:Codable{
let responseTo: String
}
struct MessageData:Codable{
let content: String
let type: String
}
struct MessageItem:Codable{
let messageId: String
let publicMeta: MessagePublicMeta?
let data: MessageData?
}
Fetching the most recent messages in given Thread:
var threadID = "THREAD_ID"
var startIndex:Int64 = 0
var pageSize:Int64 = 100
guard let privMXEndpoint = endpointContainer..getEndpoint() else {return}
guard let pagingList = try? privMXEndpoint.threadApi?
.listMessages(
from:threadID,
basedOn: .init(skip: startIndex, limit: pageSize, sortOrder: .desc)) else {return}
let messages =
pagingList.readItems.map {
MessageItem(messageId: $0.id,
publicMeta: try? JSONDecoder().decode(MessagePublicMeta.self, from: $0.publicMeta.getData() ?? Data()),
data: try? JSONDecoder().decode(MessageData.self, from: $0.data.getData() ?? Data()))
}
Managing Messages
Example of updating the message content:
var messageId = "MESSAGE_ID"
guard let privMXEndpoint = endpointContainer.getEndpoint() else {return}
guard let message = try? privMXEndpoint.threadApi?
.getMessage(messageId) else {return}
let newMessage = MessageData(content: "Hello World", type: "text")
guard let newMessageData = try? JSONEncoder().encode(newMessage) else {return}
guard let privateMeta = message.privateMeta.getData() else {return}
guard let publicMeta = message.publicMeta.getData() else {return}
try? privMXEndpoint.threadApi?
.updateMessage(message.id,
replacingData: newMessageData ,
replacingPublicMeta: privateMeta,
replacingPrivateMeta: publicMeta)