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.
Make the facade
Section titled “Make the facade”Crm lives on the main actor: make it there, and call it from there. A global the whole app reaches is the simplest:
import CrmSdkimport 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)}
@MainActorlet 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.
Start it at launch
Section titled “Start it at launch”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.
Configuration
Section titled “Configuration”CrmConfig describes your app:
| Field | What it is |
|---|---|
apiBase | Your PurrCRM address, https://app.purrcrm.com. Required. |
appKey | Your app’s key (app_…, or app_test_… in a staging build). Required. |
appVersion | Your app’s version, sent with every request and every batch of events. Required. |
productName | What your users call your app. Left out, crm.productName is the brand’s name from PurrCRM. |
storagePrefix | What 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. |
initialFeatures | The parts to assume on a phone that has never reached PurrCRM. None unless you name some. |
customEvents | Your own events, by name: see Events. |
followLifecycle | Whether the SDK follows the app to the background and back. On unless you call crm.appPaused() and crm.appResumed() yourself. |
languageTag | The 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. |
flushEvery | How often queued events are sent: 30 seconds. |
debug | Shows the setup check over the app after start(), and logs every request. Off. |
releaseBuild | Whether 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. |
logger | Where the SDK’s log lines go: the unified log (subsystem CrmSdk) unless you hand a function. |
store | Where the SDK keeps what outlives a launch: UserDefaults (DefaultsCrmStore) unless you hand another, such as MemoryCrmStore in a test. |
httpClient | The HTTP the SDK speaks through: URLSession unless you hand a CrmHttpClient, such as a fake in a test. |
clock | The clock it reads and waits on: the system’s unless a test’s. |
clipboard | The clipboard a deferred link’s claim is read from: UIPasteboard unless you hand another. |
Host hooks
Section titled “Host hooks”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 = { ... }.
| Hook | What it does | Without 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. |
links | The 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. | — |
deferredLinksFromClipboard | Whether the first run looks on the clipboard for a deferred link’s claim (Links). | Off. |
Opening the places
Section titled “Opening the places”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:
place | id | Its path |
|---|---|---|
.messenger | /messages | |
.newConversation | /messages/new | |
.conversation | the conversation’s | /messages/<id> |
.tickets | /messages/tickets | |
.ticket | the ticket’s | /messages/tickets/<id> |
.helpCenter | /help | |
.collection | the slug | /help/collections/<slug> |
.article | the slug | /help/<slug> |
.preferences | /messages/preferences | |
.message | the 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).
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.
Watching state
Section titled “Watching state”Every value the SDK keeps for your screens is a CrmValue<T>:
valueis what it is now.observe { value in … }calls you with the value now, then with every change, on the main actor. It answers aCrmCancellable: watching stops when youcancel()it or let it go, so keep it as long as the screen lives.streamis the same as anAsyncStream, 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.
In UIKit
Section titled “In UIKit”Keep the cancellables on the view controller, and redraw in the observer:
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.
In SwiftUI
Section titled “In SwiftUI”The SDK has no SwiftUI types of its own. A small bridge turns a CrmValue into an ObservableObject:
import Combineimport CrmSdk
@MainActorfinal 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 } }}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.
The app’s life cycle
Section titled “The app’s life cycle”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.