Skip to content

Instantly share code, notes, and snippets.

@vizllx
Last active September 6, 2022 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vizllx/2b316bb995d8a64c270b660596d20411 to your computer and use it in GitHub Desktop.
Save vizllx/2b316bb995d8a64c270b660596d20411 to your computer and use it in GitHub Desktop.
Getstream.io Querying Channels - Without SDK UI dependency - iOS
func getChannelList() {
// Define demo search keyword for testing
let searchKeyword = "rand"
// Declare datastore to store list of channels
var channelsList: [ChatChannel]?
// Query list of channels and conversation as per search keyword
/// NOTE: This query is optimized to search for groups which match only name instead of group member's name [JIRA Issue- CHAT-65]
let query = ChannelListQuery(filter: .or([.and([.autocomplete(.memberName, text: searchKeyword),
.containMembers(userIds: [currentUserId]), .nonEmpty, .lessOrEqual(.memberCount, than: 2)]),
.and([.autocomplete(.name, text: searchKeyword), .containMembers(userIds: [currentUserId]),
.nonEmpty])]))
// ChannelListController is only used for querying Stream Chat backend - NO SDK UI level dependency is required
let listQueryController = ChatClient.shared?.channelListController(query: query, filter: { channel in
if let name = channel.name {
return name.hasPrefix(searchKeyword)
}
return channel.name == nil && channel.membership != nil
})
// trigger the query
listQueryController?.synchronize { error in
// handle error if any
guard error == nil else {
print(error.debugDescription)
return
}
/// store list of channels in `channelsList` data store
channelsList = listQueryController?.channels.map { $0 }
guard channelsList?.count ?? 0 > 0 else {
print("No channel or conversation exist")
return
}
// print channel names which are matched by search keyword for demo purpose
/// NOTE:- In case of channel name is nil / empty it means it's a conversation channel .
/// So for Conversation channel we have to find the member name from channel object to define channel name
channelsList?.forEach {
if let name = $0.name { // i.e Channel
print("./" + name)
} else { // i.e Conversation
// find member name with Search keyword to display channel name
let members = $0.lastActiveMembers
let matchMember = members.first { obj in
obj.name?.contains(searchKeyword) ?? false
}
print("./" + (matchMember?.name ?? "Unknown User"))
}
// Show last conversation for demo purpose
let conversation = $0.latestMessages
let lastConversation = conversation.last
let author = lastConversation?.author
if author?.id == ChatClient.shared?.currentUserId {
print("./" + "You: " + (lastConversation?.text ?? ""))
} else {
if let authorName = author?.name {
print("./" + authorName + ": " + (lastConversation?.text ?? ""))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment