15-day Pro trial · no credit cardStart free →

Mobile SDKs

iOS SDK

Install the STINGIM iOS SDK with CocoaPods or as a local Swift package and add in-app chat: setup, identity, UI, events and token storage.

The iOS SDK (version 1.1.0) has two products: StingimChannel (core: connection, messages, identity — Foundation only, no third-party dependencies) and StingimChannelUI (a ready-made chat screen for UIKit and SwiftUI).

Requirements

ItemValue
Deployment targetiOS 13.0+
ToolchainXcode 16+, Swift 6.0 (swift-tools-version:6.0)
DependenciesNone (system URLSession and URLSessionWebSocketTask)
Privacy manifestIncluded (PrivacyInfo.xcprivacy; no tracking)

Install

The iOS SDK is published on this site as a source archive — no account, token or Git access needed. Use CocoaPods or add the archive to Xcode as a local Swift package.

CocoaPods

Podfile
platform :ios, '13.0'

target 'YourApp' do
  pod 'StingimChannel/UI', :podspec => 'https://stingim.com/sdk/ios/StingimChannel.podspec'   # built-in UI (includes core)
  # pod 'StingimChannel', :podspec => 'https://stingim.com/sdk/ios/StingimChannel.podspec'    # core only
end

Then run pod install. StingimChannel.podspec always describes the newest release; to pin this version use https://stingim.com/sdk/ios/StingimChannel-1.1.0.podspec instead. The podspec downloads StingimChannel-1.1.0.zip and verifies its SHA-256.

With CocoaPods the core and the UI are compiled into one module, StingimChannel. Code that should build with both CocoaPods and Swift Package Manager imports the UI conditionally:

Swift
import StingimChannel
#if canImport(StingimChannelUI)
import StingimChannelUI
#endif

Swift Package Manager (local package)

  1. Download StingimChannel-1.1.0.zip and compare shasum -a 256 StingimChannel-1.1.0.zip with the downloads page.
  2. Unzip it inside your project, for example to Vendor/StingimChannel-1.1.0 (the folder contains Package.swift). Commit it with your app so CI builds see it.
  3. In Xcode choose File → Add Package Dependencies… → Add Local… and select that folder, then add StingimChannelUI (built-in UI) or only StingimChannel (your own UI) to your app target.

In a Package.swift:

Package.swift
dependencies: [
    .package(path: "Vendor/StingimChannel-1.1.0")
],
targets: [
    .target(name: "YourApp", dependencies: [
        .product(name: "StingimChannelUI", package: "StingimChannel-1.1.0")   // built-in UI (includes core)
        // .product(name: "StingimChannel", package: "StingimChannel-1.1.0")  // core only
    ])
]

To upgrade, replace the folder with the new version and update the path.

Why no package URL?

Swift Package Manager can only resolve remote packages from a Git repository, or binary packages (binaryTarget(url:checksum:)) built as an XCFramework. The SDK is not on a public Git host and no prebuilt XCFramework is published yet, so SPM users add the source archive as a local package. CocoaPods needs no extra steps.

Initialise

Production: token from your server

Your server exchanges the App Secret for a visitor token (how) and returns contactId, contactToken and channelId:

Swift
import StingimChannel

Task {
    do {
        try await Stingim.shared.start(
            contactId: bootstrap.contactId,
            contactToken: bootstrap.contactToken,
            channelId: bootstrap.channelId,
            projectId: bootstrap.projectId,   // optional: AI disclosure / business hours
            pluginId: bootstrap.pluginId)     // optional: same
    } catch {
        print("Support chat failed to start: \(error)")
    }
}

start connects the WebSocket automatically (unless autoConnect is off). Calling start again is safe and refreshes the identity. To refresh an expired token without user interaction, set a handler:

Swift
Stingim.shared.reauthenticationHandler = {
    let b = try await MyBackend.fetchStingimToken()
    return (contactId: b.contactId, contactToken: b.contactToken)
}

Development: SDK exchanges the App Secret

Only for development or controlled environments. Never put the App Secret in the app binary, Info.plist or remote config.

Swift
import StingimChannel

Task {
    do {
        try await Stingim.shared.start(
            pluginId:  "<plugin_id>",
            appSecret: "<app_secret>",
            channelId: "<channel_id>")
    } catch {
        print("Support chat failed to start: \(error)")
    }
}

Configuration

Call configure before start:

Swift
var cfg = StingimConfig()
cfg.apiBaseUrl    = "https://api.stingim.com"   // default
cfg.socketBaseUrl = "wss://msg.stingim.com"     // default (without /visitor)
cfg.autoConnect   = true                        // connect after start
cfg.cacheMessages = true                        // local offline cache
cfg.debugMode     = false                       // logs via print("[Stingim] …"), never tokens or message content
Stingim.shared.configure(cfg)

Other fields: heartbeatIntervalSec (25), inactivityTimeoutSec (60), backoff (unlimited retries, capped at 30 s), deviceId, reconnectOnForeground (true), reconnectOnNetworkChange (true).

User identity

Sign the logged-in user on your server exactly as for the web widget: user_hash = hex(HMAC-SHA256(secret, user_id)), or of "\(user_id):\(exp)" with an expiry. In production send the signed fields to open-create-contact from your server. In direct mode pass them to the SDK:

Swift
let identity = StingimUserIdentity(userId: user.id, userHash: signed.hash, userHashExp: signed.exp,
                                   userName: user.name, userEmail: user.email)
try await Stingim.shared.start(pluginId: pid, appSecret: secret, channelId: cid, identity: identity)
print(Stingim.shared.identityStatus)   // .verified / .unverified / .rejected / .anonymous

userId must be 1–255 characters without control characters, and userHash 64 hex characters. On logout call await Stingim.shared.disconnect().

Built-in chat UI

UIKit:

Swift
import StingimChannelUI

let chat = StingimChatViewController(title: "Support")
present(UINavigationController(rootViewController: chat), animated: true)

SwiftUI:

Swift
import StingimChannelUI

struct ContentView: View {
    @State private var showChat = false
    var body: some View {
        Button("Contact support") { showChat = true }
            .sheet(isPresented: $showChat) {
                StingimChatView(title: "Support")   // includes a navigation bar
            }
    }
}

Theme the built-in UI before presenting it:

Swift
var theme = StingimTheme()
theme.primary = .systemIndigo
StingimTheme.current = theme

StingimTheme fields: primary, background, selfBubble, selfText, otherBubble, otherText, notificationText, timeText, inputBackground.

Add these Info.plist keys, or the app crashes when the user picks a photo, opens the camera or records voice: NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSMicrophoneUsageDescription.

Custom UI

Swift
import StingimChannel

final class ChatViewModel: StingimDelegate {
    private var conversationId = ""

    init() {
        Stingim.shared.delegate = self   // weak reference: keep the view model alive
        Task {
            try? await Stingim.shared.start(contactId: contactId, contactToken: contactToken, channelId: channelId)
            conversationId = await Stingim.shared.resolveActiveConversationId() ?? ""
            let page = try? await Stingim.shared.fetchMessages(pageSize: 50)
            // render page?.messages
        }
    }

    func send(_ text: String) {
        Task { await Stingim.shared.send(conversationId: conversationId, text: text) }
    }

    func stingimDidReceiveMessage(_ m: StingimMessage) { /* append to your list */ }
    func stingimDidUpdateQueue(_ i: StingimQueueInfo) { /* i.queuePosition */ }
}

Common operations:

Swift
let s = Stingim.shared

await s.send(conversationId: cid, text: "Hello")
try await s.sendImage(conversationId: cid, imageData: jpegData)
try await s.sendFile(conversationId: cid, fileData: data, fileName: "report.pdf")

let page = try await s.fetchMessages(pageSize: 20)
await s.markRead(conversationId: cid)
await s.setTyping(conversationId: cid, isTyping: true)

let unread = try await s.fetchUnreadCount()
let queue  = try await s.fetchQueueInfo(conversationId: cid)
try await s.submitEvaluation(conversationId: cid, score: 5, remark: "Great")

let cached = s.cache?.load(conversationId: cid)   // offline cache for instant first paint
  • For the very first message pass "" as conversationId; the SDK adopts the real id when the server creates the conversation.
  • Files are uploaded directly to storage, up to 20 MB each. Show incoming media with previewURL(for:) (signed URLs, cached for 10 minutes).
  • submitEvaluation throws when there is no pending rating invitation.

Delegate events

All StingimDelegate methods are optional and called on the main thread; async methods can be called from any thread.

MethodWhen
stingimDidConnect() / stingimDidDisconnect(reason:) / stingimDidError(_:)Connection state
stingimOnlineReady()The session is ready
stingimDidReceiveMessage(_:)New message
stingimDidFailToSend(localId:error:)A send failed (for example rate limited)
stingimRequiresResync(conversationId:fromSeq:reason:)Gap detected; refetch history
stingimDidUpdateQueue(_:)Queue position changed
stingimDidChangeConversationStatus(conversationId:status:)Conversation status changed
stingimDidChangeTyping(conversationId:userId:userName:userType:isTyping:)Agent typing
stingimDidReceiveReceipt(messageId:localId:status:timestamp:)Delivery / read receipt
stingimDidReceiveEvaluationInvite(_:)Ask the customer for a rating
stingimDidUpdateUnreadCount(conversationId:unreadCount:)Unread count changed
stingimDidReceiveRobotReplyDelta(conversationId:messageId:delta:chunkIndex:)Streaming AI reply
stingimDidReceiveEvent(kind:conversationId:payload:)Any other gateway event
stingimDidFailAuthentication(_:)Token rejected (StingimError.unauthorized)
stingimDidChangeContact(contactId:identityStatus:)Identity changed — reload conversations and history

StingimError cases: notConnected, tokenUnavailable, encoding, decoding, http(Int, String?), server, network, unauthorized(String), unsupported(String); isTokenInvalid tells you to fetch a new token.

Token storage

The visitor token is stored in the Keychain with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly; the contact id and similar non-secret values are in UserDefaults. disconnect() deletes all of it, including the local message cache. In direct mode, a token the server rejects (HTTP 401 or business code 502) is cleared and the SDK starts a fresh anonymous session; in token mode it calls your reauthenticationHandler. session_evicted (the same visitor connected elsewhere) is not retried automatically.

Not supported in 1.0

  • getConversationDetail (agent-only on the backend).

See Troubleshooting.

Found a mistake? Email [email protected]