Код: Выделить всё
//MARK: - Connect to the rooms which already joined
func connectToRooms(_ roomId : String?){
guard let session = getSession() else{
return
}
_ = isRoomExists(roomId) { success in
print("checking room availability : \(success)")
guard let room = session.room(withRoomId: roomId!) else {
// Handle the case where the room is not found
return
}
_ = room.liveTimeline({ timeLne in
if let _ = timeLne{
timeLne?.listenToEvents { (event, direction, roomState) in
switch direction {
case .forwards:
// This is a live, new event coming in.
// You can check if the event is a message using its type.
print("Received new message: \(event.content)")
case .backwards:
// This is an historical event retrieved via pagination.
// Process and display historical messages.
print("Received historical message: \(event.content)")
}
}
}
})
}
}
func isRoomExists(_ roomID : String?,completion:@escaping CompletionHandler){
var allKnownRooms : [MXRoom?] = []
guard let session = getSession() else{
return
}
session.start { response in
guard response.isSuccess else {
print("Failed to start session: \(response.error?.localizedDescription ?? "Unknown error")")
return
}
allKnownRooms = session.rooms
let isRoomKnown = allKnownRooms.contains { $0?.roomId == roomID! }
if !isRoomKnown {
print("Error: Room \(roomID!) is not available in the current session.")
}else{
}
completion(isRoomKnown)
}
}
func getSession()->MXSession?{
guard let mxSession = MXSession(matrixRestClient: getRestClient()) else {
// Handle error creating session
return nil
}
return mxSession
}
func getRestClient() -> MXRestClient{
let credentials = MXCredentials(homeServer: server,
userId: UserDefaults.standard.value(forKey: "UserID") as! String,
accessToken: UserDefaults.standard.value(forKey: "AccessToken") as! String)
// Create the REST client and then the session.
return MXRestClient(credentials: credentials)
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... dk-swift-i
Мобильная версия