### Display Content Cards with BrazeUI Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Demonstrates how to display Braze Content Cards using the SDK's built-in UI components. This includes pushing the content cards view controller onto a navigation stack, presenting it modally, and customizing its appearance with various attributes like corner radius, highlight color, and fonts. It also shows how to handle click actions. ```swift import BrazeKit import BrazeUI import UIKit class ContentCardsManager { // Push content cards onto navigation stack func pushContentCardsViewController(from navigationController: UINavigationController, braze: Braze) { let viewController = BrazeContentCardUI.ViewController(braze: braze) viewController.delegate = self navigationController.pushViewController(viewController, animated: true) } // Present content cards modally func presentModalContentCards(from viewController: UIViewController, braze: Braze) { let modalViewController = BrazeContentCardUI.ModalViewController(braze: braze) modalViewController.viewController.delegate = self viewController.present(modalViewController, animated: true) } // Present with custom attributes func presentCustomizedContentCards(from viewController: UIViewController, braze: Braze) { var attributes = BrazeContentCardUI.ViewController.Attributes.defaults attributes.pullToRefresh = false attributes.cellAttributes.cornerRadius = 16 attributes.cellAttributes.highlightColor = .systemGreen attributes.cellAttributes.titleFont = .italicSystemFont(ofSize: 16) attributes.cellAttributes.shadow = nil let modalViewController = BrazeContentCardUI.ModalViewController( braze: braze, attributes: attributes ) viewController.present(modalViewController, animated: true) } } extension ContentCardsManager: BrazeContentCardUIViewControllerDelegate { func contentCard( _ controller: BrazeContentCardUI.ViewController, shouldProcess clickAction: Braze.ContentCard.ClickAction, card: Braze.ContentCard ) -> Bool { // Return false to handle click action yourself return true } } ``` -------------------------------- ### Initialize Braze SDK in AppDelegate Source: https://github.com/braze-inc/braze-swift-sdk/blob/main/README.md This snippet demonstrates how to initialize the Braze SDK within your application's AppDelegate. It requires your Braze API key and endpoint. The initialized SDK instance is stored for later use. ```swift import BrazeKit class AppDelegate: UIResponder, UIApplicationDelegate { // ... static var braze: Braze? = nil // ... func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // ... let configuration = Braze.Configuration( apiKey: "YOUR-APP-IDENTIFIER-API-KEY", endpoint: "YOUR-BRAZE-ENDPOINT" ) let braze = Braze(configuration: configuration) AppDelegate.braze = braze // ... } } ``` -------------------------------- ### Implement Delayed Braze SDK Initialization Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Initialize the Braze SDK later in the app lifecycle while ensuring push notification handling is preserved. This involves preparing for delayed initialization and then calling the initialization method when ready. Dependencies include BrazeKit. ```swift import BrazeKit import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { static var braze: Braze? = nil func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Prepare Braze for delayed initialization // Push notifications received before init will be processed during initialization Braze.prepareForDelayedInitialization(pushAutomation: true) return true } // Call this when ready to initialize Braze static func initializeBraze() { let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) configuration.logger.level = .info configuration.push.appGroup = "group.com.yourapp.PushStories" configuration.push.automation = true let braze = Braze(configuration: configuration) AppDelegate.braze = braze } } ``` -------------------------------- ### Utilize Braze SDK with Swift Concurrency Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Leverage modern Swift concurrency features with the Braze SDK, including async/await APIs for asynchronous operations like content card refreshes and observing updates. Also demonstrates synchronous retrieval of user and device IDs. Dependencies include BrazeKit. ```swift import BrazeKit class AsyncBrazeManager { // Async content cards refresh func refreshCardsAsync(braze: Braze) async throws -> [Braze.ContentCard] { return try await braze.contentCards.requestRefresh() } // Async stream for content card updates func observeContentCards(braze: Braze) async { for await cards in braze.contentCards.cardsStream { print("Received \(cards.count) cards") } } // Get user ID synchronously func getUserId(braze: Braze) -> String? { return braze.user.id } // Get device ID synchronously func getDeviceId(braze: Braze) -> String { return braze.deviceId } } ``` -------------------------------- ### Display Braze Banner Cards with UIKit and SwiftUI Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Implement banner card display using either UIKit or SwiftUI. This involves requesting banner refreshes, defining banner views, and checking for banner availability. Dependencies include BrazeKit, BrazeUI, SwiftUI, and UIKit. ```swift import BrazeKit import BrazeUI import SwiftUI import UIKit // Request banner refresh at app launch func setupBanners(braze: Braze) { braze.banners.requestBannersRefresh(placementIds: [ "banner-placement-1", "banner-placement-2" ]) } // SwiftUI Banner View @available(iOS 13.0, *) struct BannerContentView: View { static let placementID = "banner-placement-1" @State var hasBanner: Bool = false @State var contentHeight: CGFloat = 0 var body: some View { VStack { Text("Your Content Here") .frame(maxWidth: .infinity, maxHeight: .infinity) if let braze = AppDelegate.braze, hasBanner { BrazeBannerUI.BannerView( placementId: Self.placementID, braze: braze, processContentUpdates: { result in switch result { case .success(let updates): if let height = updates.height { self.contentHeight = height } case .failure: break } } ) .frame(height: min(contentHeight, 80)) } } .onAppear { AppDelegate.braze?.banners.getBanner(for: Self.placementID) { banner in hasBanner = banner != nil } } } } // Check for banner availability func checkBannerAvailability(braze: Braze, placementId: String, completion: @escaping (Bool) -> Void) { braze.banners.getBanner(for: placementId) { banner in completion(banner != nil) } } ``` -------------------------------- ### Configure Braze Location Services Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Enable location tracking and geofences for location-based campaigns by configuring Braze SDK. This involves setting up location providers, enabling automatic collection, and defining geofence parameters. Dependencies include BrazeKit and BrazeLocation. ```swift import BrazeKit import BrazeLocation import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { static var braze: Braze? = nil func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) // Configure location services configuration.location.brazeLocationProvider = BrazeLocationProvider() configuration.location.automaticLocationCollection = true configuration.location.geofencesEnabled = true configuration.location.automaticGeofenceRequests = true configuration.location.allowBackgroundGeofenceUpdates = true configuration.location.distanceFilter = 5000 // meters let braze = Braze(configuration: configuration) AppDelegate.braze = braze return true } } ``` -------------------------------- ### Integrate BrazeUI for In-App Messages Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Configures the Braze SDK to use the built-in BrazeUI components. It includes delegate methods for customizing presentation context, handling clicks, and tracking presentation events. ```swift import BrazeKit import BrazeUI import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { static var braze: Braze? = nil func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) let braze = Braze(configuration: configuration) AppDelegate.braze = braze // Enable GIF support (requires SDWebImage) GIFViewProvider.shared = .sdWebImage // Setup in-app message UI let inAppMessageUI = BrazeInAppMessageUI() inAppMessageUI.delegate = self braze.inAppMessagePresenter = inAppMessageUI return true } } extension AppDelegate: BrazeInAppMessageUIDelegate { func inAppMessage( _ ui: BrazeInAppMessageUI, prepareWith context: inout BrazeInAppMessageUI.PresentationContext ) {} func inAppMessage( _ ui: BrazeInAppMessageUI, shouldProcess clickAction: Braze.InAppMessage.ClickAction, buttonId: String?, message: Braze.InAppMessage, view: InAppMessageView ) -> Bool { return true } func inAppMessage( _ ui: BrazeInAppMessageUI, didPresent message: Braze.InAppMessage, view: InAppMessageView ) { print("In-app message presented: \(message.data.id)") } } ``` -------------------------------- ### Configure Push Stories Content Extension Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Sets up a Notification Content Extension target to support push story carousels. This requires subclassing the BrazePushStory NotificationViewController. ```swift // NotificationViewController.swift in your Notification Content Extension target import BrazePushStory class NotificationViewController: BrazePushStory.NotificationViewController {} ``` -------------------------------- ### Configure Rich Push Notification Service Extension Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Sets up the Notification Service Extension required to display rich media, such as images, in push notifications. This involves subclassing the BrazeNotificationService within a dedicated target. ```swift import BrazeNotificationService class NotificationService: BrazeNotificationService.NotificationService {} ``` -------------------------------- ### BrazeUI Content Cards Integration Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Methods for displaying Content Cards using the pre-built BrazeUI components, including navigation stack pushing and modal presentation with custom styling. ```APIDOC ## BrazeUI Content Cards ### Description Use the BrazeUI library to display Content Cards via built-in ViewControllers. Supports both navigation-based pushing and modal presentation. ### Method Swift Class Methods ### Parameters - **navigationController** (UINavigationController) - Required - The controller to push the card UI onto. - **viewController** (UIViewController) - Required - The parent controller for modal presentation. - **braze** (Braze) - Required - The active Braze instance. - **attributes** (BrazeContentCardUI.ViewController.Attributes) - Optional - Custom styling for the UI (e.g., cornerRadius, titleFont). ### Request Example let attributes = BrazeContentCardUI.ViewController.Attributes.defaults attributes.cellAttributes.cornerRadius = 16 let modal = BrazeContentCardUI.ModalViewController(braze: braze, attributes: attributes) ``` -------------------------------- ### Configure SDK Authentication in Swift Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Implements the BrazeSDKAuthDelegate to handle secure user identification and authentication errors. This snippet demonstrates setting the delegate and changing users with a provided signature. ```swift import BrazeKit class SecureAuthManager: BrazeSDKAuthDelegate { func setupSDKAuthentication(braze: Braze) { // Set the SDK authentication delegate braze.sdkAuthDelegate = self } func changeUserWithAuth(braze: Braze, userId: String, signature: String) { // Change user with SDK authentication signature braze.changeUser(userId: userId, sdkAuthSignature: signature) } // BrazeSDKAuthDelegate method func braze(_ braze: Braze, sdkAuthenticationFailedWithError error: Braze.SDKAuthenticationError) { print("SDK authentication failed: \(error)") // Handle authentication failure - typically refresh the signature } } ``` -------------------------------- ### Implement Manual Push Notification Delegates in Swift Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Provides full control over push notification lifecycle by manually registering device tokens and implementing UNUserNotificationCenterDelegate methods. This is required for custom handling logic beyond the SDK defaults. ```swift import BrazeKit import UIKit import UserNotifications @main class AppDelegate: UIResponder, UIApplicationDelegate { static var braze: Braze? = nil func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) configuration.push.appGroup = "group.com.yourapp.PushStories" let braze = Braze(configuration: configuration) AppDelegate.braze = braze application.registerForRemoteNotifications() let center = UNUserNotificationCenter.current() center.setNotificationCategories(Braze.Notifications.categories) center.delegate = self center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in print("Notification authorization granted: \(granted)") } return true } func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { AppDelegate.braze?.notifications.register(deviceToken: deviceToken) } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { if let braze = AppDelegate.braze, braze.notifications.handleBackgroundNotification( userInfo: userInfo, fetchCompletionHandler: completionHandler ) { return } completionHandler(.noData) } } extension AppDelegate: @preconcurrency UNUserNotificationCenterDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { if let braze = AppDelegate.braze, braze.notifications.handleUserNotification( response: response, withCompletionHandler: completionHandler ) { return } completionHandler() } func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { if let braze = AppDelegate.braze { braze.notifications.handleForegroundNotification(notification: notification) } if #available(iOS 14, *) { completionHandler([.list, .banner]) } else { completionHandler(.alert) } } } ``` -------------------------------- ### Manual Push Notification Integration Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Provides full control over push notification handling by manually implementing UNUserNotificationCenterDelegate methods. ```APIDOC ## Manual Push Integration ### Description Manually register for remote notifications and handle notification lifecycle events through the UNUserNotificationCenterDelegate. ### Key Methods - **register(deviceToken: Data)** - Registers the device token with Braze. - **handleUserNotification(response: UNNotificationResponse, ...)** - Processes notification taps. - **handleForegroundNotification(notification: UNNotification)** - Manages display of notifications while the app is in the foreground. ### Implementation Example ```swift func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { AppDelegate.braze?.notifications.register(deviceToken: deviceToken) } ``` ``` -------------------------------- ### Implement Custom In-App Message Presenter Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Creates a custom presenter by conforming to BrazeInAppMessagePresenter. This allows developers to manually handle different message types like slideups, modals, and full-screen messages. ```swift import BrazeKit import UIKit struct CustomInAppMessagePresenter: BrazeInAppMessagePresenter { func present(message: Braze.InAppMessage) { switch message { case .slideup(let slideup): presentSlideup(slideup) case .modal(let modal): presentModal(modal) case .full(let full): presentFull(full) case .html(let html): presentHTML(html) default: break } } private func presentSlideup(_ slideup: Braze.InAppMessage.Slideup) {} private func presentModal(_ modal: Braze.InAppMessage.Modal) {} private func presentFull(_ full: Braze.InAppMessage.Full) {} private func presentHTML(_ html: Braze.InAppMessage.Html) {} } ``` -------------------------------- ### Log Purchases Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Records revenue-generating events in Braze. Allows tracking of individual product purchases with currency, price, and additional metadata properties. ```swift import BrazeKit class PurchaseManager { func userDidPurchase(productId: String, price: Double, checkoutId: String) { AppDelegate.braze?.logPurchase( productId: productId, currency: "USD", price: price, properties: [ "checkout_id": checkoutId, "payment_method": "credit_card" ] ) } func logMultiplePurchases(items: [(id: String, price: Double)]) { for item in items { AppDelegate.braze?.logPurchase( productId: item.id, currency: "USD", price: item.price ) } } } ``` -------------------------------- ### Configure Automatic Push Notifications in Swift Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Enables automatic push notification handling by setting the automation flag in the Braze configuration. This approach minimizes boilerplate code while allowing optional subscription to notification events. ```swift import BrazeKit import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { static var braze: Braze? = nil var notificationSubscription: Braze.Cancellable? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) configuration.logger.level = .info configuration.push.appGroup = "group.com.yourapp.PushStories" // Enable automatic push notification handling configuration.push.automation = true let braze = Braze(configuration: configuration) AppDelegate.braze = braze // Subscribe to push notification events notificationSubscription = AppDelegate.braze?.notifications.subscribeToUpdates { payload in print("Push notification received:") print("- type: \(payload.type)") print("- title: \(String(describing: payload.title))") print("- isSilent: \(payload.isSilent)") } return true } } ``` -------------------------------- ### Automatic Push Notification Integration Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Enables automatic handling of push notifications by setting the automation flag in the Braze configuration. ```APIDOC ## Automatic Push Integration ### Description Configures the Braze SDK to automatically handle push notification registration and lifecycle events. ### Configuration - **configuration.push.automation** (Bool) - Required - Set to true to enable automatic handling. - **configuration.push.appGroup** (String) - Required - The App Group identifier for sharing data between the app and notification service extension. ### Implementation Example ```swift let configuration = Braze.Configuration(apiKey: brazeApiKey, endpoint: brazeEndpoint) configuration.push.automation = true configuration.push.appGroup = "group.com.yourapp.PushStories" let braze = Braze(configuration: configuration) ``` ``` -------------------------------- ### Identify Users and Set Attributes Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Updates the current user context and synchronizes user profile data with Braze. Supports standard attributes like email and custom attributes for personalized segmentation. ```swift import BrazeKit class AuthenticationManager { struct User { let id: String let email: String let birthday: Date } func userDidLogin(_ user: User) { AppDelegate.braze?.changeUser(userId: user.id) let brazeUser = AppDelegate.braze?.user brazeUser?.set(email: user.email) brazeUser?.set(dateOfBirth: user.birthday) brazeUser?.setCustomAttribute(key: "last_login_date", value: Date()) brazeUser?.setCustomAttribute(key: "premium_member", value: true) brazeUser?.setCustomAttribute(key: "loyalty_points", value: 1500) } } ``` -------------------------------- ### Change User in Braze SDK Source: https://github.com/braze-inc/braze-swift-sdk/blob/main/README.md This code snippet shows how to change the current user within the Braze SDK. This is useful for tracking user activity and personalizing experiences. It requires the SDK to be initialized first. ```swift AppDelegate.braze?.changeUser(userId: "Jane Doe") ``` -------------------------------- ### Track Custom Events Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Logs specific user actions as custom events to Braze. Includes support for passing dictionary properties to provide deeper context for analytics and campaign triggering. ```swift import BrazeKit import UIKit class CheckoutViewController: UIViewController { var checkoutId: String = "" var productIds: [String] = [] override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) AppDelegate.braze?.logCustomEvent( name: "open_checkout_controller", properties: [ "checkout_id": checkoutId, "product_ids": productIds, "item_count": productIds.count ] ) } } ``` -------------------------------- ### Access Content Cards Data for Custom UI Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Provides methods to directly access and manage Braze Content Card data, enabling the creation of custom user interfaces. This includes fetching current cards, handling different card types, requesting manual refreshes, subscribing to real-time updates, canceling subscriptions, and retrieving the count of unviewed cards. ```swift import BrazeKit import UIKit class CustomContentCardsManager { var cardsSubscription: Braze.Cancellable? // Access current content cards func printCurrentContentCards(braze: Braze) { let cards = braze.contentCards.cards for card in cards { // Access common card data print("Card ID: \(card.id)") print("Extras: \(card.extras)") print("URL: \(card.clickAction?.url ?? "none")") // Handle specific card types switch card { case .classic(let classic): print("Classic card - title: \(classic.title)") case .classicImage(let classicImage): print("Classic image - title: \(classicImage.title)") print("Image URL: \(classicImage.image)") case .imageOnly(let imageOnly): print("Image only - image: \(imageOnly.image)") case .captionedImage(let captionedImage): print("Captioned image - title: \(captionedImage.title)") case .control: print("Control card (not displayed)") @unknown default: break } } } // Refresh content cards func refreshContentCards(braze: Braze) { braze.contentCards.requestRefresh { result in switch result { case .success(let cards): print("Refreshed \(cards.count) cards") case .failure(let error): print("Refresh error: \(error)") } } } // Subscribe to content card updates func subscribeToContentCards(braze: Braze) { cardsSubscription = braze.contentCards.subscribeToUpdates { cards in print("Content cards updated: \(cards.count) cards") } } // Cancel subscription func cancelSubscription() { cardsSubscription?.cancel() } // Get unviewed cards count func getUnviewedCount(braze: Braze) -> Int { return braze.contentCards.unviewedCards.count } } ``` -------------------------------- ### Rich Push Notifications Service Extension Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Enables rich media support (images) in push notifications by subclassing the BrazeNotificationService. ```APIDOC ## Rich Push Notification Service Extension ### Description To support rich push notifications, create a Notification Service Extension target and subclass the Braze provided service. ### Implementation Example ```swift import BrazeNotificationService class NotificationService: BrazeNotificationService.NotificationService {} ``` ``` -------------------------------- ### Custom Content Cards Data Access Source: https://context7.com/braze-inc/braze-swift-sdk/llms.txt Methods for accessing raw Content Card data, subscribing to updates, and manually refreshing the card feed for custom UI implementations. ```APIDOC ## Custom Content Cards Data Access ### Description Access the underlying Braze.ContentCard objects to build custom UI layouts. Includes methods for refreshing data and subscribing to real-time updates. ### Methods - **braze.contentCards.cards**: Access the current array of cards. - **braze.contentCards.requestRefresh**: Manually trigger a network refresh. - **braze.contentCards.subscribeToUpdates**: Register a closure to receive updates when cards change. ### Response - **cards** (Array) - A collection of card objects including .classic, .classicImage, .imageOnly, and .captionedImage types. ### Example braze.contentCards.requestRefresh { result in if case .success(let cards) = result { print("Received \(cards.count) cards") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.