Skip to content

Initialise the SDK

Do this once: make the facade (Crm), keep it for the life of the app, start it at launch, and hand it the hooks it needs to open your screens.

Crm lives on the main actor: make it there, and call it from there. A global the whole app reaches is the simplest:

AppCrm.swift
import CrmSdk
import Foundation
/// Asks your backend for the signed-in user's token (see "Sign users in").
let crmTokens = CrmFetchedTokens {
guard let token = try await MyBackend.shared.crmToken() else { return nil }
return CrmFetchedToken(token)
}
@MainActor
let crm = Crm(
config: CrmConfig(
apiBase: URL(string: "https://app.purrcrm.com")!,
appKey: Bundle.main.object(forInfoDictionaryKey: "CrmAppKey") as? String ?? "",
appVersion: Bundle.main.object(
forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""),
auth: .tokens(crmTokens))

CrmAppKey is a key of your own in Info.plist, so that a staging build can carry the test app’s key (Test mode). You may write the key in the code instead: it is not a secret.

AppDelegate.swift
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Task { await crm.start() }
return true
}

start() reads your app’s public face from PurrCRM once: its name, accent, logo, which parts are switched on, its link base and languages. It keeps the answer on the phone, so the next start has it at once, even offline; crm.publicApp holds it. It also restores the events an earlier launch left, records app_opened (and app_updated after an update), starts following the app to the background and back, and on the first run looks for a link through an install. Calling it again does nothing.

Then tell it who is signed in, and when they are past your own first steps.

CrmConfig describes your app:

FieldWhat it is
apiBaseYour PurrCRM address, https://app.purrcrm.com. Required.
appKeyYour app’s key (app_…, or app_test_… in a staging build). Required.
appVersionYour app’s version, sent with every request and every batch of events. Required.
productNameWhat your users call your app. Left out, crm.productName is the brand’s name from PurrCRM.
storagePrefixWhat every key the SDK keeps in UserDefaults starts with: crm unless you name one. Pick it once and never change it, or queued events are lost.
initialFeaturesThe parts to assume on a phone that has never reached PurrCRM. None unless you name some.
customEventsYour own events, by name: see Events.
followLifecycleWhether the SDK follows the app to the background and back. On unless you call crm.appPaused() and crm.appResumed() yourself.
languageTagThe user’s language, asked for on every request (Accept-Language), so articles and refusals come in it: the phone’s first preferred language unless you hand a function of your own.
flushEveryHow often queued events are sent: 30 seconds.
debugShows the setup check over the app after start(), and logs every request. Off.
releaseBuildWhether this is a build your users install. The SDK cannot tell for sure, so say it; it is used for the warnings in Test mode. false unless you say.
loggerWhere the SDK’s log lines go: the unified log (subsystem CrmSdk) unless you hand a function.
storeWhere the SDK keeps what outlives a launch: UserDefaults (DefaultsCrmStore) unless you hand another, such as MemoryCrmStore in a test.
httpClientThe HTTP the SDK speaks through: URLSession unless you hand a CrmHttpClient, such as a fake in a test.
clockThe clock it reads and waits on: the system’s unless a test’s.
clipboardThe clipboard a deferred link’s claim is read from: UIPasteboard unless you hand another.

CrmHost is how the SDK reaches your app. Every hook is optional and is called on the main actor; leaving one out means the SDK does without it. Hand them to Crm(config:auth:host:), or set them later, as your navigation comes up: crm.host.navigate = { ... }.

HookWhat it doesWithout it
navigate(destination)Shows one of PurrCRM‘s places (the messenger, a conversation, an article…) in your navigation; answers true when it did. Tapped pushes, links and crm.open(_:) go through it.Those places go nowhere.
followable(path)Your allow-list: where a link in PurrCRM‘s content (/offers/123) goes in your app, or nil for nowhere.Links into your app go nowhere.
openInApp(location)Goes to a place followable allowed.The same.
openExternal(url)Opens an https page.UIApplication’s open.
timeZone()The phone’s IANA time zone.TimeZone.current.
askPermission(permission)Asks the phone for a permission a carousel’s button asks for (.notifications, .location); answers whether it was given.The button just goes on.
onUnreadChanged(before, after)The messenger’s unread count changed.Watch crm.unread instead.
linksThe places in your app a link may go, for your team’s link picker (Links).Your team types paths by hand.
linkOpened(link)Hears of every link the SDK follows, with a saved link’s data (Links).Nothing else is told.
installReferrer()An install referrer, for a deferred link. Android’s; unused on iOS unless you have your own.—
deferredLinksFromClipboardWhether the first run looks on the clipboard for a deferred link’s claim (Links).Off.

navigate is handed a CrmDestination: a place and, for some, an id (a conversation’s, ticket’s or message’s id, or a collection’s or article’s slug). You draw each place:

placeidIts path
.messenger/messages
.newConversation/messages/new
.conversationthe conversation’s/messages/<id>
.tickets/messages/tickets
.ticketthe ticket’s/messages/tickets/<id>
.helpCenter/help
.collectionthe slug/help/collections/<slug>
.articlethe slug/help/<slug>
.preferences/messages/preferences
.messagethe message’s/messages/show/<id>

These are also the links PurrCRM writes in a reply, a push or an article. .message never reaches your hook: the SDK fetches that in-app message and puts it first in the queue for you to draw (In-app messages).

AppDelegate.swift
crm.host.navigate = { destination in
guard let navigation = AppRouter.navigation else { return false }
let screen: UIViewController
switch destination.place {
case .messenger: screen = MessengerViewController()
case .newConversation: screen = ConversationViewController(session: crm.newConversation())
case .conversation: screen = ConversationViewController(session: crm.conversation(destination.id))
case .ticket: screen = TicketViewController(id: destination.id)
case .article: screen = ArticleViewController(slug: destination.id)
case .preferences: screen = PreferencesViewController()
default: return false
}
navigation.pushViewController(screen, animated: true)
return true
}

From your own code, await crm.open(.messenger) goes through the same hook. crm.mayOpen(destination) says whether someone is signed in and has the part the place needs.

Every value the SDK keeps for your screens is a CrmValue<T>:

  • value is what it is now.
  • observe { value in … } calls you with the value now, then with every change, on the main actor. It answers a CrmCancellable: watching stops when you cancel() it or let it go, so keep it as long as the screen lives.
  • stream is the same as an AsyncStream, ending when its task does.

The facade’s own: crm.unread (the messenger’s unread count), crm.notices, crm.ready, crm.publicApp, crm.appFeatures, crm.sessionValue and crm.testPhone; and each part’s state.

Keep the cancellables on the view controller, and redraw in the observer:

HomeViewController.swift
final class HomeViewController: UIViewController {
private var watching: [CrmCancellable] = []
private let badge = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
watching.append(crm.unread.observe { [weak self] unread in
self?.badge.text = unread > 0 ? "\(unread)" : nil
self?.badge.isHidden = unread == 0
})
}
}

When the view controller goes, so do its cancellables, and the watching stops.

The SDK has no SwiftUI types of its own. A small bridge turns a CrmValue into an ObservableObject:

Watched.swift
import Combine
import CrmSdk
@MainActor
final class Watched<T: Sendable & Equatable>: ObservableObject {
@Published private(set) var value: T
private var watching: CrmCancellable?
init(_ source: CrmValue<T>) {
value = source.value
watching = source.observe { [weak self] in self?.value = $0 }
}
}
MessagesButton.swift
import SwiftUI
struct MessagesButton: View {
@ObservedObject var unread: Watched<Int> // made once, by whoever owns the screen
let open: () -> Void
var body: some View {
Button(action: open) {
Text(unread.value > 0 ? "Messages (\(unread.value))" : "Messages")
}
}
}

On iOS 14 and later, a view can own its Watched with @StateObject. On iOS 15 and later, a view can also read the stream itself:

.task { for await n in crm.unread.stream { unread = n } }

A SwiftUI app on iOS 13 has a scene delegate and a UIHostingController, so the app delegate and scene delegate code on these pages applies as written. With the SwiftUI App life cycle (iOS 14), reach them through @UIApplicationDelegateAdaptor.

With followLifecycle on (the default), the SDK listens for the app going to the background and coming back. On the way out it records session_ended and sends the queued events, inside a background task so that iOS lets it finish; on the way back it records app_opened, checks in for messages, and reads the messenger and the inbox again. A conversation on screen stops listening in the background and starts again on return.

await crm.dispose() stops everything for good (the queue is kept for the next launch). An app rarely needs it.

Sign users in.