Chapter 5. Usage examples

Table of Contents

Simple client sending message
Simple client setting presence and handling incoming presences
Simple client setting presence, handling incoming presences and responding on incoming messages
Simple client with support for MUC
Simple client with support for PubSub

Simple client sending message

Below is example code of client which send XMPP message to as using Pa$$w0rd as password for authentication. Message is sent just after clients connects to server, authenticates and establishes session.

import Foundation
import TigaseSwift

class MessageSendingClient: EventHandler {

    var client: XMPPClient;

    init() {

        client = XMPPClient();


        print("Notifying event bus that we are interested in SessionEstablishmentSuccessEvent" +
            " which is fired after client is connected");
        client.eventBus.register(handler: self, for: SessionEstablishmentModule.SessionEstablishmentSuccessEvent.TYPE);
        print("Notifying event bus that we are interested in DisconnectedEvent" +
            " which is fired after client is connected");
        client.eventBus.register(handler: self, for: SocketConnector.DisconnectedEvent.TYPE);

        setCredentials(userJID: "", password: "Pa$$w0rd");

        print("Connecting to server..")
        print("Started async processing..");

    func registerModules() {
        print("Registering modules required for authentication and session establishment");
        _ = client.modulesManager.register(AuthModule());
        _ = client.modulesManager.register(StreamFeaturesModule());
        _ = client.modulesManager.register(SaslModule());
        _ = client.modulesManager.register(ResourceBinderModule());
        _ = client.modulesManager.register(SessionEstablishmentModule());

        print("Registering module for sending/receiving messages..");
        _ = client.modulesManager.register(MessageModule());

    func setCredentials(userJID: String, password: String) {
        let jid = BareJID(userJID);

    /// Processing received events
    func handle(event: Event) {
        switch (event) {
        case is SessionEstablishmentModule.SessionEstablishmentSuccessEvent:
        case is SocketConnector.DisconnectedEvent:
            print("Client is disconnected.");
            print("unsupported event", event);

    /// Called when session is established
    func sessionEstablished() {
        print("Now we are connected to server and session is ready..");

        let messageModule: MessageModule = client.modulesManager.getModule(MessageModule.ID)!;
        let recipient = JID("");
        let chat = messageModule.createChat(with: recipient);
        print("Sending message to", recipient, "..");
        _ = messageModule.sendMessage(in: chat!, body: "I'm now online..");

        print("Waiting 1 sec to ensure message is sent");
        print("Disconnecting from server..");