Sariska provides a Swift API and easy-to-integrate SDKs for building real-time features into your iOS, macOS, watchOS, and tvOS applications. Easily add in-app chats, instant messaging, and other real-time functionalities to your apps.
Key Features:
Real-time messaging for in-app chats and instant messaging
Easy installation using Cocoa Pods or Carthage
Socket creation and management
Channel creation, joining, and leaving
Sending messages, poll votes, and message replies
Presence management (track: typing, joining and leaving users)
History management (fetching chat history and specific messages)
Installation
Step 1 : Install the Phoenix Client
Using Cocoa Pods
To install SwiftPhoenixClient using CocoaPods, add the following line to your Podfile:
pod"SwiftPhoenixClient",'~> 2.0'
To use Swift Phoenix Client, the minimum iOS target must be '9.0'.
If you are using RxSwift extensions, add the following line to your Podfile:
pod"SwiftPhoenixClient/RxSwift",'~> 2.0'
If your version requirements require iOS 13 and below, add the following line to your Podfile:
pod"SwiftPhoenixClient/Starscream",'~> 2.0'
Using Carthage
To install SwiftPhoenixClient using Carthage, add the following line to your Cartfile:
github"davidstump/SwiftPhoenixClient"~>2.0
Step 2 : Create Socket
To establish a connection with Sariska's real-time messaging platform, you'll need to create a socket instance. This socket will handle joining channels, receiving events, and sending messages.
To disconnect the user from any previous WebSocket connections and tabs before opening a new one, set the disconnect_past_tabs parameter to true in the WebSocket connection.
Disconnect Socket
Close the WebSocket connection to the Sariska server. This will terminate all active channels and prevent further communication with the server.
/// Close connection to the serversocket.disconnect()/// Removes all event callback hooks, such as 'onOpen' and onClosesocket.releaseCallback()
Step 3 : Create Channel
Channels cannot be created directly; instead, they are created through the socket object by calling socket.channel(topic) with the topic of the channel. The topic is a string that identifies the channel, and it can be any string you like.
Channel Prefix
Each channel name starts with a prefix that determines the message serialization format and persistence behavior.
chat: Use this prefix for persisting messages to the database. This prefix requires a fixed schema and is ideal for chat applications.
let channel = socket.channel("chat:room123");
rtc: Use this prefix for scenarios where message persistence is not necessary. This prefix allows sending arbitrary JSON data, making it suitable for events in multiplayer games, IoT applications, and others.
let channel = socket.channel("rtc:room123");
sariska: Use this prefix for performance-critical applications that utilize Flatbuffers as the serialization format and do not require message persistence. This prefix provides zero-copy serialization/deserialization, significantly enhancing performance.
let channel = socket.channel("sariska:room123");
Handle Errors
When an error occurs on the channel, the onError callback is triggered. The callback receives the error information in payload, if available.
When the channel is closed, the onClose callback is invoked. This signifies that the communication on the channel has ended and no further data can be exchanged.
To join a channel, call the join() method on the channel object. The join() method returns a promise that resolves when the client has successfully joined the channel. When sending data, you can utilize the .receive() hook to monitor the status of the outgoing push message.
/// Join the Channelchannel.join() .receive("ok") { message inprint("Channel Joined", message.payload) } .receive("error") { message inprint("Failed to join", message.payload) }/// Leave the Channelchannel.leave()
Channel User Joined
/// Subscribe to the "new_user" event, when new user join the roomchannel.on("new_user") { [weak self](message)in/// Extract the username from the message payloadlet username = message.payload["username"]as?String/// Print a message indicating that the new user has joined the roomprint("\(username) has joined the room!")}
Payload of user containing user details, including:
id: The user's ID
name: The user's name
avatar: The user's avatar URL
email: The user's email address
Payload of room containing room details, including:
id: The room's ID
session_id: The room's session ID
created_by: The ID of the user who created the room
status: The status of the room (e.g., "active", "inactive")
Channel New Message
channel.on("new_msg") { [weak self](message)in/// Extract the payload from the messagelet payload = message.payload/// Extract the content from the payloadlet content = payload["content"]as?String/// Extract the username from the payloadlet username = payload["username"]as?String/// Print the message to the consoleprint("\(username) sent the message: \(content)")}
Payload of message containing message details, including:
content: The message content
id: The sender's user ID
name: The sender's name
content_type: The message content type (media, emoji, text)
is_delivered: Whether the message has been delivered to the recipient
created_by: The ID of the user who sent the message
created_by_name: The name of the user who sent the message
timestamp: The message timestamp
Send Message
Once you've established a connection to a channel, you can start sending messages to other connected clients. To send a message, use the push() method on the channel object.
channel/// Send a message with payload .push("new_messgage", payload: ["body":"message body"])/// Receive a response message .receive("ok", handler: { (payload) in print("Message Sent") })
Send Message Reply
channel/// Send a message with payload .push("new_messgage_reply", payload: ["body":"message body"])/// Receive a response message .receive("ok", handler: { (payload) in print("Message Sent") })
Channel Poll Vote
let pollOptions = ["Option 1", "Option 2", "Option 3"]/// Build the payload with the poll question, content type, and optionslet payload: [String:Any] = ["content":"poll question?","content_type":"poll","options": pollOptions]/// Send the new_vote event with the payloadchannel .push("new_vote", payload: payload) .receive("ok", handler: { (payload) in print("Poll Vote Sent") })
Payload of new_vote containing vote details, including:
content: The vote question
content_type: The vote content type (media, emoji, text)
options: An array of vote options
For other polls APIs, please refer toSwagger documentation
Attach Media Files to Chat Messages
Attaching media files to chat messages involves obtaining a presigned URL, uploading the file to the presigned URL, and then sending the file information to the chat server.
Obtain a Presigned URL
To obtain a presigned URL, make a POST request to the API endpoint. The request payload should be empty, and the Authorization header should contain your bearer token. The bearer token authenticates the request and returns a URL that can be used to upload content.
importFoundationfuncgetPresignedURL() asyncthrows-> URL {let url =URL(string:"https://api.sariska.io/api/v1/misc/get-presigned")!var request =URLRequest(url: url)/// Set the HTTP method to `POST` request.httpMethod ="POST"/// Add bearer token to the Authorization header request.setValue("Bearer your-token", forHTTPHeaderField:"Authorization")let(data, _)=tryawait URLSession.shared.data(from: request)let responseBody =tryJSONDecoder().decode(ResponseBody.self, from: data)returnURL(string: responseBody.presignedUrl)!}
Upload the File
After obtaining the presigned URL, the file can be uploaded to the URL using the PUT method.
funcuploadFile(fileURL: URL) asyncthrows {/// Retrieve the pre-signed URL for uploading the filelet presignedURL =tryawaitgetPresignedURL()/// Read the contents of the file into a `Data` objectlet fileData =tryData(contentsOf: fileURL)/// Create a `URLRequest` object with the pre-signed URLvar request =URLRequest(url: presignedURL)/// Set the HTTP method to `PUT` request.httpMethod ="PUT"/// Set the ACL header to "public-read" to make the file publicly accessible request.setValue("public-read", forHTTPHeaderField:"ACL")/// Set the Content-Disposition header to "attachment" to indicate that the response is a file attachment request.setValue("attachment", forHTTPHeaderField:"Content-Disposition")/// Upload the file data using the `URLSession` objecttryawait URLSession.shared.upload(for: request, from: fileData)}/// Codable struct to represent the response bodystructResponseBody:Codable {let presignedUrl: String}
Example usage demonstration
let fileURL =/// URL to the file you want to uploaddo {tryawaituploadFile(fileURL: fileURL)print("File uploaded successfully.")} catch {print("Error uploading file: \(error)")}
Use presignedUrl to upload your files
Chat History
Retrieve the chat history using two methods:
By Subscribing to Events
Subscribe to the archived_message event to receive the last 1000 archived messages in reverse chronological order.
channel.on("archived_message") { (payload) iniflet messages = payload["messages"]as? [String:Any] {/// Print the received messagesprint("Received archived messages: \(messages)") }}
Subscribe to the archived_message_count event to get the total number of messages in the chat history.
To retrieve a list of messages in the chat history, trigger the archived_message event to obtain the messages. Specify the size parameter to determine the number of messages you wish to fetch, and set the offset parameter as the starting index of the messages and group_by_day to group messages by day.
To receive the total count of messages at any given time, initiate the archived_message_count trigger and subscribe to the corresponding event by listening for archived_message_count.
channel.push("archived_message_count")
Using the Messages API
Make a GET request to the API endpoint to fetch the chat history for a specific room.
funcfetchChatHistory(completion: @escaping (Result<[String:Any], Error>) ->Void) {/// Construct the request URLlet url =URL(string:"https://api.sariska.io/api/v1/messaging/rooms/{room_name}/messages")!/// Modify the request to use the GET methodvar request =URLRequest(url: url) request.httpMethod ="GET" request.addValue("Bearer your-token", forHTTPHeaderField:"Authorization")/// Send the GET request to the API endpoint URLSession.shared.dataTask(with: request) { (data, response, error) in/// Check for errorsiflet error = error {completion(.failure(error))return }/// Check for successful responseguardlet httpResponse = response as? HTTPURLResponse, httpResponse.statusCode ==200else {let statusCode = (response as? HTTPURLResponse)?.statusCode ??-1let errorMessage ="Failed with status code \(statusCode)"let error =NSError(domain:"APIError", code: statusCode, userInfo: [NSLocalizedDescriptionKey: errorMessage])completion(.failure(error))return }/// Parse the response datado {iflet data = data {let json =try JSONSerialization.jsonObject(with: data, options: [])as? [String:Any]completion(.success(json ?? [:])) } else {completion(.success([:])) } } catch {completion(.failure(error)) } }.resume()}
Example usage demonstration
fetchChatHistory { result inswitch result {case .success(let chatHistory):print("Chat history: \(chatHistory)")case .failure(let error):print("Error fetching chat history: \(error)") }}
Fetch Specific Message
Retrieve any specific message from a room. It takes the room ID and message ID as parameters and sends a GET request to the Sariska API to fetch the specified message.
funcfetchSpecificMessage(messageID: String, completion: @escaping (Result<[String:Any], Error>) ->Void) {/// Construct the request URLlet urlString ="https://api.sariska.io/api/v1/messaging/rooms/{room_name}/messages/\(messageID)"guardlet url =URL(string: urlString)else {completion(.failure(NSError(domain:"InvalidURL", code:-1, userInfo: [NSLocalizedDescriptionKey:"Invalid URL"])))return }/// Construct the requestvar request =URLRequest(url: url) request.httpMethod ="GET" request.addValue("Bearer your-token", forHTTPHeaderField:"Authorization")/// Send the GET request to the API endpoint URLSession.shared.dataTask(with: request) { (data, response, error) in// Check for errorsiflet error = error {completion(.failure(error))return }/// Check for successful responseguardlet httpResponse = response as? HTTPURLResponse, httpResponse.statusCode ==200else {let statusCode = (response as? HTTPURLResponse)?.statusCode ??-1let errorMessage ="Failed with status code \(statusCode)"let error =NSError(domain:"APIError", code: statusCode, userInfo: [NSLocalizedDescriptionKey: errorMessage])completion(.failure(error))return }/// Parse the response datado {iflet data = data {let json =try JSONSerialization.jsonObject(with: data, options: [])as? [String:Any]completion(.success(json ?? [:])) } else {completion(.success([:])) } } catch {completion(.failure(error)) } }.resume()}
Example usage demonstration
let messageId ="your-message-id"fetchSpecificMessage(messageID: messageId) { result inswitch result {case .success(let specificMessage):print("Specific message: \(specificMessage)")case .failure(let error):print("Error fetching specific message: \(error)") }}
Presence
The Presence object facilitates real-time synchronization of presence information between the server and the client, enabling the detection of user join and leave events.
Create a Presence Instance
To establish presence synchronization, instantiate a Presence object and provide the channel to track presence lifecycle events:
let channel = socket.channel("some:topic")let presence =Presence(channel)
Custom Event Options
By default, the Presence object uses built-in events for syncing state changes. However, you can configure the Presence object to use custom events instead. This allows you to better integrate with your existing application logic.
let options =Options(events: [.state:"my_state", .diff:"my_diff"])let presence =Presence(channel, opts: options)
.state: Custom event name for state changes
.diff: Custom event name for presence diff updates
State Synchronization
The presence.onSync callback triggers whenever the server updates the presence list. This allows you to update your UI based on the latest presence information, such as dynamically generating a user list.
presence.onSync { renderUsers(presence.list()) }
Handle Individual Join and Leave Events
To handle individual join and leave events, use the presence.onJoin and presence.onLeave callbacks. These provide information about the user and their presence state. Here is an instance:
let presence =Presence(channel)/// Detect if the user has joined for the first time or from another tab/devicepresence.onJoin { [weak self](key, current, newPres)iniflet cur = current {print("user additional presence", cur) } else {print("user entered for the first time", newPres) }}/// Detect if the user has left all tabs/devices, or is still presentpresence.onLeave { [weak self](key, current, leftPres)inif current["metas"]?.isEmpty==true {print("user has left from all devices", leftPres) } else {print("user left from a device", current) }}/// Receive presence data from serverpresence.onSync { renderUsers(presence.list()) }
Retrieve Presence Information
The presence.list(by:) method retrieves a list of presence information based on the local metadata state. By default, it returns the entire presence metadata. Alternatively, a listBy function can be provided to filter the metadata for each presence.
For instance, if a user is online from multiple devices, each with a metadata status of "online," but their status is set to "away" on another device, the application might prefer to display the "away" status in the UI.
The following example defines a listBy function that prioritizes the first metadata registered for each user, representing the first tab or device they used to connect:
let listBy: (String, Presence.Map) -> Presence.Meta = { id, pres inlet first = pres["metas"]!.first! first["count"]= pres["metas"]!.count/// Set the user ID for the presence metadata first["id"]= id/// Return the prioritized presence metadatareturn first}/// Retrieve a list of online users based on the prioritized presence metadatalet onlineUsers = presence.list(by: listBy)
This example prioritizes the first registered metadata for each user, representing their first connected tab or device. If the user is online from multiple devices, their status in the UI will reflect the first device they used to connect.
User Typing
Send information about a user who is typing. This information can be used to update the chat interface, such as displaying a "user is typing" indicator next to the user's name.
Send User Typing Event
When a user starts typing, the following code sends a typing event to other peers.
The Sariska client library offers an optional API to automatically manage retain cycles for event hooks, simplifying your code and preventing memory leaks.
How it works:
Each event hook has a corresponding delegate*(to:) method.
This method takes a reference to an owner object and passes it back to the event hook.
When the owner object is deinitialized, the associated event hook is automatically dereferenced, preventing retain cycles.
Benefits:
Cleaner API: Eliminates the need for [weak self] capture lists, making your code more concise and readable.