Reference
iOS API
Every public type, method and property in the four iOS libraries (core, UI, notification service and Live Activity), with signatures, parameters and threading notes.
This page lists every public symbol in the iOS SDK, version 0.4.0, grouped by area. It is written from the package source. The package has four libraries:
| Library | Import | Platforms | Use it in |
|---|---|---|---|
HeraldSDK | import HeraldSDK | iOS 16, macOS 13 | Your app target |
HeraldUI | import HeraldUI | iOS 16 | Your app target, for the default feed and in-app views |
HeraldNotificationService | import HeraldNotificationService | iOS 16 | Your Notification Service Extension target only |
HeraldLiveActivity | import HeraldLiveActivity | iOS 16 (Live Activities need iOS 18) | Your widget extension target, for Live Activities |
HeraldPushStory | import HeraldPushStory | iOS 16 | Your Notification Content Extension target only, for push stories (0.7.0+) |
Threading
- Every method on
Heraldcan be called from any thread. It returns at once, never throws, and runs in the order you called it. Invalid input is logged and skipped. - Calls made before
configureare kept, up to 1,000, and applied once it runs. Later ones are dropped with a warning. - Members marked main actor must be used from the main actor:
inAppMessageDelegate,inAppMessagePresenter,deepLinkHandler,openDeepLink(_:),ContentCardStoreand everything inHeraldUI.
Setup
Herald.configure
static func configure(_ configuration: HeraldConfiguration)
static func configure(appKey: String, endpoint: URL, options: (inout HeraldConfiguration) -> Void = { _ in })Starts the SDK. Call it once, early in app launch. A second call is ignored with a warning.
| Parameter | Type | Description |
|---|---|---|
configuration | HeraldConfiguration | All settings |
appKey | String | The connection's app key, from the Mobile SDK card |
endpoint | URL | Your Herald base URL, for example https://YOUR_HERALD_HOST |
options | closure | Changes settings on a configuration that starts from the defaults |
Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!) { options in
options.deviceDataCollection = .minimal
options.logLevel = .debug
}Herald.shared, Herald.sdkVersion
static let shared: Herald
static let sdkVersion: String // "0.6.0"shared is the only instance. sdkVersion is sent with every batch.
HeraldConfiguration
struct HeraldConfiguration: Sendable {
init(appKey: String, endpoint: URL)
}| Property | Type | Default | Description |
|---|---|---|---|
appKey | String | Sent as the x-herald-app-key header | |
endpoint | URL | Base URL of the Herald API | |
deviceDataCollection | DeviceDataCollection | .standard | Which device data tiers are sent |
flushInterval | TimeInterval | 10 | Seconds between automatic flushes in the foreground |
flushAt | Int | 20 | Queued event count that starts a flush |
foregroundSessionTimeout | TimeInterval | 1800 | Seconds of inactivity in the foreground before the next activity starts a new session. A cold start within it of the last activity continues the session. 0.6.0 and later. |
backgroundSessionTimeout | TimeInterval | 1800 | Seconds in the background before the next activity starts a new session. 0.6.0 and later. |
sessionTimeout | TimeInterval | 1800 | Deprecated in 0.6.0. Setting it sets both timeouts; reading it returns foregroundSessionTimeout. |
trackLifecycleEvents | Bool | true | Sends $app_installed, $app_updated, $app_opened, $app_foreground and $app_background (Lifecycle events). 0.6.0 and later. |
trackDeepLinks | Bool | true | Sends $deep_link_opened when a deep link goes through openDeepLink or a push tap. 0.6.0 and later. |
trackDeepLinkQuery | Bool | false | Adds the link's query string to $deep_link_opened. Off by default because a query can hold personal data. 0.6.0 and later. |
maxQueuedEventAge | TimeInterval | 2592000 | Seconds (30 days). Queued events older than this are dropped before a batch is built and counted in dropped; Herald rejects SDK events more than 30 days old. 0.6.0 and later. |
inAppMinimumInterval | TimeInterval | 30 | Minimum seconds between two triggered in-app messages |
logLevel | HeraldLogLevel | .warning | Lowest level written to the unified log |
crashReports | Bool | false | iOS only. When true, sends Apple MetricKit crash and hang reports to Herald (POST /api/v1/sdk/diagnostics). A report holds no user id and no device id. iOS delivers a report on the next launch after a crash, usually the day after. Reports that fail to send wait on the device (newest 50) and go out on the next launch. Nothing is sent while the SDK is disabled, and wipeData() deletes waiting reports. |
trackExternalPushes | Bool | true | 0.6.0+. Records a tapped push that isn't from Herald, forwarded to handleNotificationResponse, as $external_push, so the push limit counts it. Silent pushes and local notifications are never recorded. |
DeviceDataCollection
enum DeviceDataCollection: String, Sendable { case standard, minimal }| Case | Sends |
|---|---|
standard | Tier 1 and tier 2: adds time zone, locale, language, device model, screen, push permission and network type |
minimal | Tier 1 only: device ID, app, OS, SDK version, region, sessions and message interactions |
HeraldLogLevel
enum HeraldLogLevel: Int, Sendable, Comparable { case none, error, warning, info, debug }Identity
identify
func identify(userId: String, traits: [String: HeraldValue] = [:])Identifies the current user. A different ID from the current one ends the session, clears the previous user's token, cards and messages, and starts a new session. After identifying, the SDK sends the device's push token again for this user, and fetches the user's messages when the device was anonymous.
| Parameter | Type | Description |
|---|---|---|
userId | String | Your stable user ID, 1 to 200 characters. The console calls it the External ID. |
traits | [String: HeraldValue] | Attributes to merge into the profile. Keys 1 to 255 characters; values string, number, bool, null or an array of strings |
setUserToken
func setUserToken(_ token: String?)Sets the identity verification token for the current user: the hex HMAC-SHA256 of the External ID, minted by your backend. nil or an empty string clears it. Call it immediately after identify. A new token starts a fetch of the user's cards and messages. See Users and identity.
reset
func reset()Signs the user out on this device. Ends the session, clears the External ID, token, cards, in-app messages and pending messages, starts a new anonymous session and sends the push token again. The device ID stays. In-app history is kept per user.
heraldId
var heraldId: String? { get }The User ID of the identified person, such as "7K3M-9QXA", for a "Support ID" line on your settings or help screen. nil until the first accepted batch for the user the batch is verified as (any claimed user under Off; never under Optional without a token), and again after reset() or a switch to another user. Cached across launches. Read-only and safe from any thread. See Support ID.
Events and attributes
track
func track(_ event: String, properties: [String: HeraldValue] = [:], schemaVersion: String? = nil)Records a custom event and evaluates in-app messages with an event trigger.
| Parameter | Type | Description |
|---|---|---|
event | String | Event name, 1 to 255 characters |
properties | [String: HeraldValue] | Any JSON values; keys up to 255 characters; numbers must be finite |
schemaVersion | String? | 0.6.0 and later. The event schema version to check the event against, such as "1-0-0". nil (the default) checks it against the latest version. A value that isn't a version like 1-0-0 is left off with a debug log; the event is still sent |
trackExternalPush
func trackExternalPush(messageId: String? = nil, category: ExternalPushCategory = .other, source: String? = nil)0.6.0+. Reports a push your app sent itself, as $external_push, so the push limit counts it. Never include the push's title or body.
| Parameter | Type | Description |
|---|---|---|
messageId | String? | Up to 200 characters. The same ID your backend reports, so the push counts once |
category | ExternalPushCategory | .transactional, .marketing or .other |
source | String? | Up to 100 characters, such as "orders" |
A longer messageId or source is logged and the call is skipped.
screen
func screen(_ name: String, properties: [String: HeraldValue] = [:])Records a screen view. Same rules as track. Screen views do not trigger in-app messages.
trackPurchase
func trackPurchase(productId: String, price: Double, currency: String, quantity: Int = 1, properties: [String: HeraldValue] = [:])| Parameter | Type | Description |
|---|---|---|
productId | String | 1 to 255 characters |
price | Double | Finite number |
currency | String | 3-letter ISO 4217 code; converted to upper case |
quantity | Int | 1 or more |
properties | [String: HeraldValue] | Same rules as track |
setAttribute, setAttributes
func setAttribute(_ key: String, _ value: HeraldValue)
func setAttributes(_ attributes: [String: HeraldValue])Merges attributes into the user's profile. Keys 1 to 255 characters; values string, finite number, bool, null or an array of strings. Do not start your own keys with $. An invalid $email or $phone is dropped with a warning and the other keys are sent.
setEmail, setPhone
func setEmail(_ email: String?)
func setPhone(_ phone: String?)Set the reserved $email and $phone attributes, which Herald stores as the user's email and SMS contacts. The phone number must be E.164, for example +15551234567. nil sends a null value. An invalid value is dropped with a warning.
setSubscription
func setSubscription(_ channel: SubscriptionChannel, _ state: SubscriptionState)
enum SubscriptionChannel: String, Sendable, Codable { case push, email, sms }
enum SubscriptionState: String, Sendable, Codable { case subscribed, unsubscribed, optedIn } // optedIn = "opted_in"Records the user's opt-in state for a channel. A push opt-in made before the APNs token exists waits for the token. An opt-out is sent at once.
setLocation
func setLocation(latitude: Double, longitude: Double)Stores a location your app obtained itself, as the reserved $latitude and $longitude attributes on the device record. Latitude must be -90 to 90 and longitude -180 to 180; other values are logged and skipped. The SDK never reads location on its own.
Consent
0.6.0+.
func setConsent(basis: ConsentBasis, documentId: String? = nil, documentVersion: String? = nil)
func clearConsent()Records the lawful basis your app collects data under. ConsentBasis is .consent, .contract, .legalObligation, .vitalInterests, .publicTask or .legitimateInterests (the GDPR lawful bases). documentId and documentVersion name your policy or terms, at most 100 characters each; a longer one is logged and the call skipped. The record and the time of the call are persisted and sent in each batch's context.consent until clearConsent(). Herald keeps it on the device and on the person, where admins see it on the person's page.
This is a record for your compliance, not enforcement: it doesn't change what the SDK collects. Use deviceDataCollection or setEnabled(false) for that. See Consent and opt-out.
Remote config
0.6.0+. The SDK fetches the app's SDK settings (Settings, SDK settings in the console) at launch and on a foreground at most once an hour, with no user or device id. It caches the last good response on disk and applies the cached one at launch, before the fetch. A remote value overrides flushInterval, foregroundSessionTimeout, backgroundSessionTimeout, deviceDataCollection, trackLifecycleEvents, trackExternalPushes or trackDeepLinks; a setting left at "Use app's value" keeps yours. A network or parse error keeps what is applied, and startup never waits for the fetch. Nothing is fetched while setEnabled(false) is in effect.
With "Collect events" off, the SDK records and sends nothing (crash reports included), skips message syncs and clears its queue. Push tokens and subscription changes are still queued, not sent, and go out when collection resumes, with the current push token, so a device that registered or unsubscribed meanwhile isn't lost. It keeps fetching config, so turning it back on resumes collection. The cached settings belong to the app key they were fetched with: a different key starts from your configuration.
var remoteConfigVersion: String? { get }The version of the settings in use (cached or fetched), for debugging; nil before any was fetched.
Data control
| Method | Description |
|---|---|
func flush() | Sends queued events now, unless a server-requested retry delay is still running |
func flush(timeout: Duration) async -> Bool | 0.5.0+. Sends queued events now and waits. Returns true once every event recorded before the call has been accepted by Herald; false on timeout, offline, inside a server-requested retry delay, while the SDK is off, or when Herald refused an event (a dropped batch, or an event listed in rejected). Events recorded after the call don't hold it up. |
func setEnabled(_ enabled: Bool) | Turns all collection, sending and message display off or on. Persisted across launches. Turning it off first sends one best-effort push unsubscribe for the device and hides cached content cards until it is turned back on. Turning it back on re-sends the push token and a push subscription of subscribed when the device still has its token and notification permission. |
var isEnabled: Bool | Read-only. false after setEnabled(false) or wipeData() until setEnabled(true). Reflects those calls at once; before configure has loaded the state it reads the saved opt-out from disk. Cheap and safe from any thread. |
func wipeData() | Sends one best-effort push unsubscribe for the device, then deletes every file and record the SDK keeps on the device (cached cards included), generates a new device ID and leaves the SDK off until setEnabled(true) |
Push
requestPushAuthorization
func requestPushAuthorization() async -> BoolAsks for alert, sound and badge permission. When granted, registers with APNs. Records the push subscription: opted in (sent after the APNs token arrives) or unsubscribed. Returns whether permission was granted; false on platforms without push.
setPushToken
func setPushToken(_ token: Data)Forward the token from application(_:didRegisterForRemoteNotificationsWithDeviceToken:). The SDK sends it as lowercase hex, with the APNs environment (sandbox for simulator and development-signed builds, production otherwise) and your bundle ID.
handleNotificationResponse
@discardableResult nonisolated func handleNotificationResponse(_ response: UNNotificationResponse) -> Bool
@discardableResult nonisolated func handleNotificationResponse(userInfo: [AnyHashable: Any], actionIdentifier: String) -> BoolForward from userNotificationCenter(_:didReceive:withCompletionHandler:). Callable from any isolation. Returns false when the notification did not come from Herald.
$app_opened reports from_push: true only when this call reaches the SDK before the app becomes active. Scene-based apps, including SwiftUI apps, usually get the response after activation, so they usually report false even for a launch from a push.
| Action | What the SDK logs | Then |
|---|---|---|
| Default tap | A push open | Evaluates push_open triggers; opens the push's deeplink |
| Action button | A push open, then a button with the button ID | Evaluates push_open triggers; opens the button's deeplink, else the push's |
| Dismiss (category with a custom dismiss action) | A push dismiss | Nothing opens |
Opens and button taps are logged at most once per decision.
With trackExternalPushes on, a tap (not a dismiss) on a push that isn't from Herald is recorded as $external_push and the call returns false. Its message_id is the payload key herald_external_id, else the notification's request identifier; its category is herald_category (transactional, marketing or other), else other.
handleRemoteNotification
@MainActor func handleRemoteNotification(_ userInfo: [AnyHashable: Any]) async -> BoolHandles a Herald sync push: a silent push (content-available: 1) with herald_sync set to "1". Returns true after refreshing content cards and in-app messages (or after 25 seconds at most, so the completion handler is called within iOS's background time; before configure it starts the refresh and returns true at once), false for any other push. It never shows anything or logs an open, and skips a sync push that arrives within 30 seconds of the last one. Call it from application(_:didReceiveRemoteNotification:fetchCompletionHandler:) and pass .newData or .noData to the completion handler. Needs the Remote notifications background mode. See Silent push.
registerPushCategories
func registerPushCategories(_ categories: [HeraldPushCategory])Registers notification categories for action buttons. Categories with other IDs are kept; one with the same ID is replaced. Call at launch.
HeraldPushCategory
struct HeraldPushCategory: Sendable, Hashable {
static let maxButtons: Int // 3
let id: String
let buttons: [Button] // at most 3; extras are dropped
init(id: String, buttons: [Button])
struct Button: Sendable, Hashable {
let id: String
let title: String
let opensApp: Bool // default true; needed to open a deep link
let destructive: Bool // default false; shows the button in red
init(id: String, title: String, opensApp: Bool = true, destructive: Bool = false)
}
}A push shows these buttons when its APNs payload names the category in aps.category.
Content cards
contentCards
let contentCards: ContentCardStoreThe current user's cards. See ContentCardStore below.
refreshContentCards
func refreshContentCards()Fetches the latest cards and in-app messages now. The SDK also fetches at session start and when an anonymous device is identified.
logImpression, logClick, logDismissal (cards)
func logImpression(_ card: ContentCard)
func logClick(_ card: ContentCard)
func logDismissal(_ card: ContentCard)For custom card UIs. Each logs an interaction with the card's decision ID and updates viewed, clicked or hides the card. logDismissal hides the card on this device and remembers it. The HeraldUI feed calls these for you.
ContentCardStore
@MainActor final class ContentCardStore: ObservableObject {
@Published private(set) var cards: [ContentCard]
var updates: AsyncStream<[ContentCard]>
}Main actor. cards holds the unexpired, undismissed cards in server order. Observe it from SwiftUI with @ObservedObject. updates yields the current list at once, then every change.
ContentCard
struct ContentCard: Sendable, Hashable, Identifiable, Decodable| Property | Type | Description |
|---|---|---|
id | String | Card ID |
type | CardType | .classic, .captionedImage, .imageOnly |
title, body, cta | String? | Text |
imageUrl | URL? | Image |
url | URL? | Deep link or web URL opened on click |
extras | [String: HeraldValue] | Custom key-value data |
pinned | Bool | Pinned cards sort first in the default feed |
dismissible | Bool | Whether the user may dismiss it |
categories | [String] | Labels for filtering |
createdAt | Date | Creation time |
expiresAt | Date? | Hidden after this time |
viewed, clicked, dismissed | Bool | State (var) |
decisionId | String? | Herald decision, sent back with interactions |
videoUrl | URL? | A video to play in place of the image; imageUrl holds its poster (0.6.0) |
videoPosterUrl | URL? | The poster, the same as imageUrl |
videoAutoplay | Bool | Play muted and looped while the card is at least half visible in ContentCardFeed; false by default |
credit | MediaCredit? | The stock photo or video's creator: name, profileUrl: URL?, sourceUrl: URL?. A credit without a name is dropped. |
ContentCard.CardType is a String enum: classic, captionedImage ("captioned_image"), imageOnly ("image_only"). The memberwise init takes every property, with defaults for all but id and type.
In-app messages
inAppMessageDelegate
@MainActor var inAppMessageDelegate: InAppMessageDelegate?Main actor. Held weakly. Asked when a message is about to appear.
inAppMessagePresenter
@MainActor var inAppMessagePresenter: InAppMessagePresenter?Main actor. Draws messages. Messages are not shown while it is nil; setting it offers any pending message.
deepLinkHandler, openDeepLink
@MainActor var deepLinkHandler: ((URL) -> Bool)?
@MainActor func openDeepLink(_ url: URL)Main actor. openDeepLink passes the URL to deepLinkHandler; when the handler is nil or returns false, the system opens it. The SDK and HeraldUI use it for push, card and message clicks. From 0.6.0 each call also sends $deep_link_opened (source push for a push tap's link, link otherwise) unless trackDeepLinks is off.
showNext
func showNext()Offers the highest-priority pending message now (ties: the one pending longest), ignoring the minimum interval. The delegate is asked again. Does nothing while a message is on screen.
logVideoPlay, logVideoComplete
func logVideoPlay(_ card: ContentCard)
func logVideoComplete(_ card: ContentCard)
func logVideoPlay(_ message: InAppMessage)
func logVideoComplete(_ message: InAppMessage)For custom displays; HeraldUI already calls them, once per view, when the video first starts and first reaches the end. Each logs an interaction with action video_play or video_complete and the item's decision ID. They change no viewed, clicked or dismissed state. See Video in content cards.
logImpression, logClick, logDismissal (messages)
func logImpression(_ message: InAppMessage)
func logClick(_ message: InAppMessage, buttonId: String? = nil)
func logDismissal(_ message: InAppMessage)For custom presenters. The SDK already logs the impression when a presenter returns true, so do not call logImpression from a presenter. logClick with buttonId nil logs a body click; with an ID, a button click.
debugLoadMessages, debugShowInAppMessage
func debugLoadMessages(_ json: Data)
func debugShowInAppMessage(_ messageId: String)Debug and preview only. See Logging and debugging.
InAppMessage
struct InAppMessage: Sendable, Hashable, Identifiable, Decodable| Property | Type | Description |
|---|---|---|
id | String | Message ID |
type | MessageType | .slideup, .modal, .full, .html |
priority | Int | Higher wins when several messages match |
trigger | InAppTrigger | When it is eligible |
reEligibility | InAppReEligibility | How often it may show |
expiresAt | Date? | Not shown after this time |
content | Content | Text, image, buttons, HTML |
style | Style | Per-message colors; nil fields use the theme |
decisionId | String? | Herald decision |
Nested types:
| Type | Members |
|---|---|
InAppMessage.MessageType | slideup, modal, full, html |
InAppMessage.SlideFrom | top, bottom |
InAppMessage.ButtonAction | .close, .deeplink(URL), .url(URL); var url: URL? |
InAppMessage.Button | id: String, text: String, action: ButtonAction |
InAppMessage.Content | header, body, html: String?; imageUrl: URL?; videoUrl: URL?, videoPosterUrl: URL? (0.6.0); credit: MediaCredit?; buttons: [Button]; slideFrom: SlideFrom?; dismissAfterSeconds: Double? |
InAppMessage.Style | backgroundColor, textColor, buttonColor, buttonTextColor: String? (hex such as #101828); cornerRadius: Double? |
Every nested type has a public memberwise init with defaults, which is useful for previews and tests.
InAppTrigger, PropertyFilter, InAppReEligibility
enum InAppTrigger: Sendable, Hashable, Decodable {
case sessionStart
case event(name: String, propertyFilters: [PropertyFilter])
case pushOpen
}
struct PropertyFilter: Sendable, Hashable, Decodable {
enum Operator: String { case eq, neq, gt, gte, lt, lte, contains, exists }
let key: String
let op: Operator
let value: HeraldValue
init(key: String, op: Operator, value: HeraldValue = .null)
}
enum InAppReEligibility: Sendable, Hashable, Decodable {
case once
case afterHours(Double)
}A filter on a property that is missing or null is false for every operator, exists included.
InAppMessageDelegate
@MainActor protocol InAppMessageDelegate: AnyObject {
func shouldDisplay(_ message: InAppMessage) -> InAppMessageDisplayChoice
}
enum InAppMessageDisplayChoice: Sendable { case display, later, discard }Main actor. Can be asked more than once for the same message, so keep it free of side effects.
| Choice | Effect |
|---|---|
display | Show now |
later | Keep it pending; offered again automatically or with showNext() |
discard | Drop this occurrence; the message stays eligible for its next trigger |
InAppMessagePresenter
@MainActor protocol InAppMessagePresenter: AnyObject {
func present(_ message: InAppMessage, onClose: @escaping @MainActor @Sendable () -> Void) -> Bool
}Main actor. Return true only when the message is on screen; the SDK then logs the impression and records it as shown. Return false when it cannot show now, and do not call onClose; the message stays pending. After returning true, log clicks with logClick(_:buttonId:), log a dismissal with logDismissal(_:) when the user closed it without clicking, and call onClose exactly once when it leaves the screen. See Custom views.
Values
HeraldValue
enum HeraldValue: Sendable, Hashable, Codable {
case string(String), number(Double), bool(Bool), array([HeraldValue]), object([String: HeraldValue]), null
var stringValue: String? { get }
var numberValue: Double? { get }
var boolValue: Bool? { get }
var arrayValue: [HeraldValue]? { get }
var objectValue: [String: HeraldValue]? { get }
}A JSON value for properties, traits, attributes and card extras. It conforms to the string, integer, float, boolean, array, dictionary and nil literal protocols, so ["minutes": 32, "plan": "free"] works directly. Whole numbers are encoded without a fraction.
HeraldUI
Every HeraldUI type is main actor (SwiftUI views and the presenter) and iOS only.
Herald.useDefaultInAppUI
@MainActor @discardableResult
static func useDefaultInAppUI(theme: HeraldTheme = HeraldTheme(), viewProvider: HeraldInAppPresenter.ViewProvider? = nil) -> HeraldInAppPresenterCreates the default presenter and sets it as Herald.shared.inAppMessagePresenter. Call once after configure.
HeraldInAppPresenter
@MainActor final class HeraldInAppPresenter: InAppMessagePresenter {
typealias ViewProvider = @MainActor (InAppMessage, InAppMessageActions) -> AnyView?
var theme: HeraldTheme
var viewProvider: ViewProvider?
init(theme: HeraldTheme = HeraldTheme(), viewProvider: ViewProvider? = nil)
func present(_ message: InAppMessage, onClose: @escaping @MainActor @Sendable () -> Void) -> Bool
}Draws each message in its own window on the foreground window scene. viewProvider returns your view for a message, or nil for the default. present returns false while another message is up or when no scene is in the foreground.
InAppMessageActions
@MainActor final class InAppMessageActions {
let message: InAppMessage
func buttonClicked(_ button: InAppMessage.Button)
func bodyClicked(url: URL? = nil)
func clicked(buttonId: String)
func dismiss()
}What a message view reports. Each call after the message is down does nothing.
| Method | Logs | Then |
|---|---|---|
buttonClicked(_:) | A button click | Opens the button's URL through openDeepLink, then closes |
bodyClicked(url:) | A body click | Opens url when given, then closes |
clicked(buttonId:) | A button click (empty IDs ignored) | Keeps the message up |
dismiss() | A dismissal, only when nothing was clicked | Closes |
Message views
struct SlideupMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) }
struct ModalMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) }
struct FullScreenMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) }
struct HTMLMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) }
struct DefaultInAppMessageView: View { init(message: InAppMessage, actions: InAppMessageActions) }The default view for each type. DefaultInAppMessageView picks one by message.type.
ContentCardFeed
struct ContentCardFeed<CardContent: View>: View {
init(
filter: @escaping (ContentCard) -> Bool = { _ in true },
order: @escaping (ContentCard, ContentCard) -> Bool = ContentCardFeedDefaults.order,
emptyMessage: LocalizedStringKey = "No updates right now",
onCardClick: ((ContentCard) -> Void)? = nil,
@ViewBuilder cardContent: @escaping (_ card: ContentCard, _ onClick: @escaping () -> Void) -> CardContent
)
}
extension ContentCardFeed where CardContent == ContentCardView {
init(filter:order:emptyMessage:onCardClick:) // same defaults, default card views
}| Parameter | Description |
|---|---|
filter | Keeps the cards it returns true for |
order | Sort order (areInIncreasingOrder); pinned first, then newest, by default. Equal cards keep server order. |
emptyMessage | Shown when there are no cards; looked up in your app's strings |
onCardClick | Runs after the click is logged. When nil, the card's url goes to deepLinkHandler, then to the environment's openURL |
cardContent | Draws one card; call onClick when it is tapped |
The feed logs an impression once per card per session when at least half the card is visible. Dismissible cards can be swiped away, or dismissed with the VoiceOver "Dismiss" action.
ContentCardFeedDefaults
enum ContentCardFeedDefaults {
static func order(_ a: ContentCard, _ b: ContentCard) -> Bool // pinned first, then newest
}Card views
struct ContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) }
struct ClassicContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) }
struct CaptionedImageContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) }
struct ImageOnlyContentCardView: View { init(card: ContentCard, onClick: @escaping () -> Void) }ContentCardView picks the view for card.type. Cards are tappable only when they have a url.
HeraldImage
struct HeraldImage: View {
init(url: URL?, aspectRatio: CGFloat, accessibilityLabel: String? = nil)
}A remote image at a fixed aspect ratio, decoded at the drawn size, with a flat placeholder while it loads or when it fails. Loads https and http URLs and files inside the app bundle, up to 20 MB. Hidden from VoiceOver unless accessibilityLabel is set.
Theme
struct HeraldTheme: Sendable {
var lightColors: HeraldColors // .light
var darkColors: HeraldColors // .dark
var typography: HeraldTypography
var cornerRadius: CGFloat // 12
var spacing: CGFloat // 16
var darkMode: Bool? // nil follows the system
init(lightColors:darkColors:typography:cornerRadius:spacing:darkMode:) // all defaulted
func colors(for colorScheme: ColorScheme) -> HeraldColors
}
struct HeraldColors: Sendable, Hashable {
var background, surface, onSurface, onSurfaceVariant, accent, onAccent, outline, scrim: Color
static let light: HeraldColors
static let dark: HeraldColors
}
struct HeraldTypography: Sendable {
var title: Font // .headline
var body: Font // .subheadline
var button: Font // .subheadline.weight(.semibold)
var caption: Font // .footnote
}
struct MessageColors: Sendable, Hashable {
var background, text, button, buttonText: Color
var cornerRadius: CGFloat
init(style: InAppMessage.Style, theme: HeraldTheme, colorScheme: ColorScheme)
}
extension EnvironmentValues { var heraldTheme: HeraldTheme }
extension View { func heraldTheme(_ theme: HeraldTheme) -> some View }
extension Color { init?(heraldHex hex: String?) } // "#RRGGBB" or "#AARRGGBB"MessageColors applies a message's style fields on top of the theme. An invalid hex value falls back to the theme. See Theming and dark mode.
HeraldNotificationService
This library depends on Foundation and UserNotifications only, so it links into an app extension.
HeraldNotificationService
open class HeraldNotificationService: UNNotificationServiceExtension, @unchecked Sendable {
open var imageTimeout: TimeInterval { get } // 20
}Subclass it as your extension's principal class. It adds herald_actions buttons, then attaches the push image. When time runs out it delivers the best content it has.
HeraldRichPush
enum HeraldRichPush {
static let imageKeys: [String] // ["image_url", "image"]
static let defaultTimeout: TimeInterval // 20
static let actionsKey: String // "herald_actions"
static let maxActions: Int // 3
static func prepare(_ content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, session: URLSession = .shared) async -> UNNotificationContent
static func applyActions(to content: UNNotificationContent) async -> UNNotificationContent
static let mediaBudget: TimeInterval // 25
static func attachMedia(to content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, budget: TimeInterval = mediaBudget, session: URLSession = .shared) async -> UNNotificationContent
static func attachImage(to content: UNNotificationContent, timeout: TimeInterval = defaultTimeout, session: URLSession = .shared) async -> UNNotificationContent
static func imageURL(in userInfo: [AnyHashable: Any]) -> URL?
}| Function | Description |
|---|---|
prepare | applyActions, then attachMedia (the video, else the image). Returns the content unchanged when there is nothing to add. |
applyActions | Registers a category for the payload's herald_actions and sets it on the content. Unchanged when there are no actions or aps.category is already set. Keeps at most 10 such categories. |
attachMedia(to:timeout:budget:session:) | Attaches the push's video_url as a movie (HTTPS, video/mp4 or video/quicktime, at most 10 MB, within 60% of budget, 25 seconds by default), else the image as attachImage does. Returns the content unchanged when both fail. prepare uses it. |
attachImage | Downloads the first HTTPS image URL and attaches it. Unchanged when the download fails, times out, is over 10 MB, or is not JPEG, PNG, GIF or HEIC. |
imageURL(in:) | The first imageKeys value that is an HTTPS URL |
HeraldStory
0.7.0+. Push stories in the service extension: HeraldNotificationService attaches every page's image and registers the HERALD_STORY category (one Open button, renamed with storyOpenTitle) when the payload has herald_story.
public struct HeraldStoryPage: Equatable, Sendable {
public let imageURL: URL, title: String, subtitle: String, deeplink: URL?
}
public enum HeraldStory {
static let pagesKey: String // "herald_story"
static let category: String // "HERALD_STORY"
static let pageActionPrefix: String // "herald_story_page_"
static func attachmentId(_ index: Int) -> String // "herald-story-<index>"
static func pages(in userInfo: [AnyHashable: Any]) -> [HeraldStoryPage]
static func attachImages(to content: UNNotificationContent, pages: [HeraldStoryPage], timeout: TimeInterval, session: URLSession = .shared) async -> UNNotificationContent
}pages(in:) is empty unless at least 2 pages have an HTTPS image, a title and a subtitle.
HeraldPushStory
0.7.0+. For a Notification Content Extension; depends on HeraldNotificationService, not HeraldSDK.
open class HeraldStoryViewController: UIViewController, UNNotificationContentExtension {
open var previousTitle: String { get } // "Previous"
open var nextTitle: String { get } // "Next"
open var openTitle: String { get } // "Open"
}Make a subclass the extension's principal class and set UNNotificationExtensionCategory to HERALD_STORY. It shows one page at a time with Previous, Next and Open. Open forwards the action herald_story_page_<index> to the app, where handleNotificationResponse(_:) logs a push open and a button interaction with that id and opens the page's deep link. See Push stories.
HeraldLiveActivity
This library does not depend on HeraldSDK, so it links into a widget extension. HeraldSDK depends on it. See Live Activities setup.
HeraldActivityAttributes
public struct HeraldActivityAttributes: Codable, Hashable, Sendable { // ActivityAttributes on iOS 16.1 and later
public let campaignId: String
public let deeplink: String?
public init(campaignId: String, deeplink: String? = nil)
public struct ContentState: Codable, Hashable, Sendable {
public let title: String
public let body: String
public let progress: Double? // 0 to 1, for progress mode
public let endsAt: Double? // Unix seconds
public init(title: String, body: String, progress: Double? = nil, endsAt: Double? = nil)
}
}The attributes of the Live Activity Herald starts with a push-to-start. The type name and field names are part of the wire format, so do not wrap or rename them.
HeraldLiveActivityWidget
@available(iOS 16.1, *)
public struct HeraldLiveActivityWidget: Widget {
public init()
}Add HeraldLiveActivityWidget() to your widget extension's WidgetBundle, and set NSSupportsLiveActivities to YES in the app's Info.plist.
HeraldGeofence
0.7.0+, not released yet. Opt-in geofence monitoring, a separate library product so apps that don't use it never link CoreLocation. Depends on HeraldSDK. See Geofences.
import HeraldGeofence
extension Herald {
func enableGeofences()
func disableGeofences()
}enableGeofences() downloads the app's geofence list (GET /api/v1/sdk/geofences, no location sent) and monitors the 20 nearest with Core Location, re-picked on significant location change when there are more. Call it after configure, at every launch, once the app holds "Always" location permission; without it the call logs a warning and does nothing. The SDK never asks for permission and reads no location before this call. Crossings send $geofence_enter / $geofence_exit with geofence_id and geofence_name, at most one per geofence and direction every 5 minutes, and nothing while the SDK is off. The Geofences SDK setting set to Off stops monitoring. disableGeofences() stops monitoring Herald's regions until enableGeofences() is called again; regions your app monitors itself are never touched.