### Install Synerise SDK with Carthage Source: https://github.com/synerise/synerise-ios-sdk/blob/master/README.md Integrate the Synerise SDK using Carthage. This involves installing Carthage, updating your Cartfile, and linking the framework in your Xcode project. ```bash brew install carthage ``` ```text github "synerise/ios-sdk" ``` ```bash carthage update --use-xcframeworks --platform ios ``` -------------------------------- ### Setup and Load Content Widget Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Configure and load a ContentWidget for displaying product recommendations. This involves setting recommendation options, widget options, layout, and appearance, then attaching the widget's view to the view hierarchy. ```swift import SyneriseSDK class ProductRecommendationsViewController: UIViewController, ContentWidgetDelegate { var widget: ContentWidget? override func viewDidLoad() { super.viewDidLoad() setupRecommendationWidget() } func setupRecommendationWidget() { // Configure recommendation options let recOptions = ContentWidgetRecommendationsOptions(slug: "homepage-recommendations") recOptions.productID = "CURRENT_PRODUCT_ID" // Configure widget options let widgetOptions = ContentWidgetOptions(recommendationsOptions: recOptions) // Configure layout — horizontal scroll let itemLayout = ContentWidgetBasicProductItemLayout() let sliderLayout = ContentWidgetHorizontalSliderLayout() // Configure appearance let appearance = ContentWidgetAppearance( widgetLayout: sliderLayout, itemLayout: itemLayout ) // Create and load widget widget = ContentWidget(options: widgetOptions, appearance: appearance) widget?.delegate = self widget?.load() } // MARK: - ContentWidgetDelegate func snr_widgetDidLoad(widget: ContentWidget) { let widgetView = widget.getView() widgetView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(widgetView) NSLayoutConstraint.activate([ widgetView.leadingAnchor.constraint(equalTo: view.leadingAnchor), widgetView.trailingAnchor.constraint(equalTo: view.trailingAnchor), widgetView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), widgetView.heightAnchor.constraint(equalToConstant: 200) ]) print("Widget loaded — is loaded: \(widget.isLoaded())") } func snr_widgetDidNotLoad(widget: ContentWidget, error: Error) { print("Widget load error: \(error.localizedDescription)") } func snr_widgetDidReceiveClickAction(widget: ContentWidget, model: BaseModel) { print("Item clicked: \(model)") // Navigate to product detail screen } func snr_widgetIsLoading(widget: ContentWidget, isLoading: Bool) { // Show/hide a loading indicator } func snr_widgetDidChangeSize(widget: ContentWidget, size: CGSize) { print("Widget new size: \(size)") } } ``` -------------------------------- ### Install Synerise SDK with CocoaPods Source: https://github.com/synerise/synerise-ios-sdk/blob/master/README.md Add the Synerise SDK to your project using CocoaPods. Ensure you have CocoaPods installed and update your Podfile accordingly. ```bash gem install cocoapods ``` ```ruby platform :ios, '14.0' use_frameworks! target YOUR_PROJECT_TARGET do pod 'SyneriseSDK' end ``` ```bash pod install ``` ```bash pod update ``` -------------------------------- ### Track App Start Event Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use this function to track when the application is started. It sends a predefined ApplicationStartedEvent. ```swift func trackAppStart() { Tracker.send(ApplicationStartedEvent.event()) } ``` -------------------------------- ### Install Synerise iOS SDK with Carthage Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Add the Synerise SDK to your project using Carthage. After updating, drag the SyneriseSDK.framework from the Carthage/Build/iOS directory into your Xcode project's 'Embedded Binaries'. ```ruby # Cartfile github "synerise/ios-sdk" ``` ```bash brew install carthage carthage update --use-xcframeworks --platform ios # Drag Carthage/Build/iOS/SyneriseSDK.framework into Xcode "Embedded Binaries" ``` -------------------------------- ### Session / Lifecycle Events Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Track key user session and lifecycle events such as app start, login, logout, and registration. ```APIDOC ## `Tracker.send` — Session / Lifecycle Events ### Description These functions allow you to track important user session and lifecycle events. ### Methods - `trackAppStart()`: Sends an event indicating the application has started. - `trackLogin(label: String)`: Sends an event indicating a user has logged in. - `trackLogout(label: String)`: Sends an event indicating a user has logged out. - `trackRegistration(label: String)`: Sends an event indicating a user has registered. ### Usage Examples ```swift // Track app start Tracker.send(ApplicationStartedEvent.event()) // Track user login Tracker.send(LoggedInEvent(label: "user.loggedIn")) // Track user logout Tracker.send(LoggedOutEvent(label: "user.loggedOut")) // Track user registration Tracker.send(RegisteredEvent(label: "user.registered")) ``` ``` -------------------------------- ### Install Synerise iOS SDK with CocoaPods Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use this snippet to add the Synerise SDK to your iOS project via CocoaPods. Ensure your Podfile specifies the correct platform version and uses frameworks. ```ruby # Podfile platform :ios, '14.0' use_frameworks! target 'MyApp' do pod 'SyneriseSDK' end ``` ```bash gem install cocoapods pod install pod update # upgrade to latest version ``` -------------------------------- ### Install Synerise iOS SDK with Swift Package Manager Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Integrate the Synerise SDK into your project using Swift Package Manager. You can add it directly in Xcode or by defining the dependency in your Package.swift file. ```swift // Package.swift dependency .package(url: "https://github.com/Synerise/synerise-ios-sdk", from: "5.13.0") ``` -------------------------------- ### Initialize Synerise SDK Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Bootstrap the Synerise SDK by calling `Synerise.initialize` in your `AppDelegate`. This method requires your Profile API Key and can optionally accept a custom base URL and initialization configuration. ```swift import SyneriseSDK // AppDelegate.swift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, SyneriseDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Basic initialization Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY") // — OR — advanced initialization with private cloud URL and config let config = InitializationConfig() config.initialDoNotTrack = false config.requestValidationSalt = "YOUR_SALT" Synerise.initialize( apiKey: "YOUR_PROFILE_API_KEY", baseUrl: "https://api.your-custom-env.com", config: config ) Synerise.setDelegate(self) Synerise.setDebugModeEnabled(true) // disable in production Synerise.setCrashHandlingEnabled(true) return true } // MARK: - SyneriseDelegate func snr_initialized() { print("Synerise SDK ready") } func snr_initializationError(error: Error) { print("Synerise init failed: \(error.localizedDescription)") } func snr_registerForPushNotificationsIsNeeded() { // Re-register for push — see Client.registerForPush let token = UserDefaults.standard.string(forKey: "pushToken") ?? "" Client.registerForPush( registrationToken: token, success: { print("Push re-registered") }, failure: { err in print("Push re-registration failed: \(err.localizedDescription)") } ) } func snr_handledAction(url: URL, source: SyneriseSource) { // Route URL deep-links from campaigns UIApplication.shared.open(url) } func snr_handledAction(deepLink: String, source: SyneriseSource) { // Route custom deep-links from campaigns print("Deep-link: \(deepLink) from \(source)") } } ``` -------------------------------- ### Register New User Account Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Register a new client account with email and password, optionally providing personal details and agreements. Requires SyneriseSDK import. ```swift import SyneriseSDK func registerUser(email: String, password: String) { let context = ClientRegisterAccountContext(email: email, password: password) context.firstName = "Jane" context.lastName = "Doe" context.phone = "+48500000000" context.sex = .female context.birthDate = "1990-06-15" context.city = "Warsaw" context.countryCode = "PL" let agreements = ClientAgreements() agreements.email = true agreements.push = true agreements.sms = false context.agreements = agreements context.attributes = ["loyalty_tier": "gold", "referral_code": "REF123"] Client.registerAccount( context: context, success: { print("Registration successful — check email for activation link") // Trigger activation email Client.requestAccountActivation( email: email, success: { print("Activation email sent") }, failure: { err in print("Activation email error: \(err.localizedDescription)") } ) }, failure: { error in switch error.errorType { case .http: print("HTTP \(error.httpCode): \(error.errorBody?.message ?? "Unknown")") case .network: print("Network error — check connectivity") default: print("Error: \(error.localizedDescription)") } } ) } ``` -------------------------------- ### Promotions.getOrAssignVoucher / Promotions.assignVoucherCode Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Manages voucher assignments from a pool to the current client. Includes methods to get or assign a voucher, and to retrieve all assigned voucher codes. ```APIDOC ## `Promotions.getOrAssignVoucher` / `Promotions.assignVoucherCode` — Voucher Management Assigns voucher codes from a pool to the current client. `getOrAssignVoucher` returns an existing voucher if already assigned, otherwise creates one. `getAssignedVoucherCodes` retrieves all codes assigned to the client. ### Get or Assign Voucher ```swift func getOrAssignVoucher(poolUUID: String, success: @escaping (AssignVoucherResponse) -> Void, failure: @escaping (Error) -> Void) ``` ### Assign New Voucher Code ```swift func assignVoucherCode(poolUUID: String, success: @escaping (AssignVoucherResponse) -> Void, failure: @escaping (Error) -> Void) ``` ### Get Assigned Voucher Codes ```swift func getAssignedVoucherCodes(success: @escaping (AssignedVouchersResponse) -> Void, failure: @escaping (Error) -> Void) ``` ``` -------------------------------- ### Initialize Synerise SDK in Swift Source: https://github.com/synerise/synerise-ios-sdk/blob/master/README.md Initialize the Synerise iOS SDK with your Profile API Key. This is a required step before using any SDK features. Obtain your API Key from the Synerise account settings. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let apiKey = "YOUR_PROFILE_API_KEY" Synerise.initialize(apiKey: apiKey) } ``` -------------------------------- ### Synerise.initialize Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Initializes the Synerise SDK with your Profile API Key. This method must be called once during application launch before any other SDK operations. Overloads allow for specifying a custom base URL for private cloud environments and providing an InitializationConfig for advanced settings like initial do-not-track state and request validation salt. ```APIDOC ## Synerise.initialize(apiKey:) ### Description Bootstraps the SDK with a Profile API Key. It must be called once in `application(_:didFinishLaunchingWithOptions:)` before any other SDK call. Overloads accept an optional `baseUrl` for private cloud environments and an `InitializationConfig` for setting initial do-not-track state or a request validation salt. ### Method `Synerise.initialize(apiKey: String)` `Synerise.initialize(apiKey: String, baseUrl: String, config: InitializationConfig)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import SyneriseSDK // AppDelegate.swift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, SyneriseDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Basic initialization Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY") // — OR — advanced initialization with private cloud URL and config let config = InitializationConfig() config.initialDoNotTrack = false config.requestValidationSalt = "YOUR_SALT" Synerise.initialize( apiKey: "YOUR_PROFILE_API_KEY", baseUrl: "https://api.your-custom-env.com", config: config ) Synerise.setDelegate(self) Synerise.setDebugModeEnabled(true) // disable in production Synerise.setCrashHandlingEnabled(true) return true } // MARK: - SyneriseDelegate func snr_initialized() { print("Synerise SDK ready") } func snr_initializationError(error: Error) { print("Synerise init failed: \(error.localizedDescription)") } func snr_registerForPushNotificationsIsNeeded() { // Re-register for push — see Client.registerForPush let token = UserDefaults.standard.string(forKey: "pushToken") ?? "" Client.registerForPush( registrationToken: token, success: { print("Push re-registered") }, failure: { err in print("Push re-registration failed: \(err.localizedDescription)") } ) } func snr_handledAction(url: URL, source: SyneriseSource) { // Route URL deep-links from campaigns UIApplication.shared.open(url) } func snr_handledAction(deepLink: String, source: SyneriseSource) { // Route custom deep-links from campaigns print("Deep-link: \(deepLink) from \(source)") } } ``` ### Response #### Success Response (200) None (Initialization is synchronous and does not return a value, but delegate methods are called upon completion or error.) #### Response Example None ``` -------------------------------- ### Get or Assign Voucher Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Retrieves an existing voucher code for a pool if already assigned to the client, otherwise assigns a new one. Provides details of the assigned voucher. ```swift func getOrAssignVoucher(poolUUID: String) { Promotions.getOrAssignVoucher( poolUUID: poolUUID, success: { response in print("Message: \(response.message)") let data = response.assignVoucherData print("Voucher code: \(data.code)") print("Expires: \(data.expireIn?.description ?? "never")") print("Assigned at: \(data.assignedAt?.description ?? "N/A")") }, failure: { err in print("Voucher assignment failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Activate Promotion with Options Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Activates a promotion with additional options, such as points to use. Returns the full updated promotion model upon success. ```swift func activatePromotionWithOptions(uuid: String, pointsToUse: Int) { let identifier = PromotionIdentifier(uuid: uuid) let options = PromotionActivationOptions(identifier: identifier) options.pointsToUse = pointsToUse Promotions.activatePromotion( options: options, success: { updatedPromotion in print("Activated: \(updatedPromotion.name)") print("Status: \(updatedPromotion.status)") print("Possible redeems: \(updatedPromotion.possibleRedeems?.intValue ?? 0)") }, failure: { err in print("Options activation failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Fetch Personalized Recommendations with Options Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use `Content.getRecommendationsV2` to fetch AI-personalized recommendations. Configure options like product IDs, exclusions, filters, and display attributes. Remember to track recommendation views using `RecommendationViewEvent` and clicks using `RecommendationClickEvent`. ```swift import SyneriseSDK func loadRecommendations(slug: String, currentProductId: String) { let options = RecommendationOptions(slug: slug) options.productID = currentProductId options.productIDs = ["PROD001", "PROD002", "PROD003"] options.itemsExcluded = ["PROD_OUT_OF_STOCK"] options.additionalFilters = "category:electronics" options.filtersJoiner = .and options.displayAttribute = ["name", "price", "image_url", "category"] options.includeContextItems = true Content.getRecommendationsV2( options: options, success: { response in print("Campaign: \(response.name) [\(response.campaignHash)]") print("Correlation ID: \(response.correlationID)") print("Items: \(response.items.count)") for item in response.items { let name = item.getAttributeSetForKey("name") as? String ?? "" let price = item.getAttributeSetForKey("price") as? Double ?? 0 print(" - \(item.itemID): \(name) @ \(price)") } // Track that recommendations were viewed let viewEvent = RecommendationViewEvent( label: "recommendation.view", items: response.items.map { $0.itemID }, campaignID: response.campaignID, campaignHash: response.campaignHash, correlationId: response.correlationID, params: nil ) Tracker.send(viewEvent) }, failure: { error in print("Recommendations failed: \(error.errorBody?.message ?? error.localizedDescription)") } ) } // Track recommendation click func trackRecommendationClick( productId: String, productName: String, campaignID: String, campaignHash: String ) { let event = RecommendationClickEvent( label: "recommendation.click", productName: productName, productId: productId, campaignID: campaignID, campaignHash: campaignHash, params: nil ) event.setCategory("Electronics") Tracker.send(event) } ``` -------------------------------- ### Switch SDK Workspace at Runtime Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Switches the SDK to a different workspace at runtime without requiring app restart. Useful for multi-tenant applications or A/B workspace testing. Configure behavior on key change via settings first. ```swift import SyneriseSDK func switchWorkspace(newApiKey: String, newSalt: String?) { // Configure behaviour on key change via settings first Synerise.settings.sdk.shouldDestroySessionOnApiKeyChange = true let config = InitializationConfig() config.requestValidationSalt = newSalt Synerise.changeApiKey(newApiKey, config: config) print("SDK now operating under new API key") } ``` ```swift // Or set salt only func updateRequestSalt(salt: String) { Synerise.setRequestValidationSalt(salt) } ``` -------------------------------- ### Activate Account via PIN Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Activate a user's account using their email and a PIN code. Requires SyneriseSDK import. ```swift // PIN-based activation func activateByPin(email: String, pin: String) { Client.confirmAccountActivationByPin( pinCode: pin, email: email, success: { print("Account activated via PIN") }, failure: { err in print("PIN activation failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Initialize Synerise SDK in Objective-C Source: https://github.com/synerise/synerise-ios-sdk/blob/master/README.md Initialize the Synerise iOS SDK with your Profile API Key in Objective-C. Ensure you have obtained your API Key from the Synerise account settings. ```objective-c - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { static NSString *apiKey = @"YOUR_PROFILE_API_KEY"; [SNRSynerise initializeWithApiKey:apiKey]; } ``` -------------------------------- ### Fetch Dynamic Document with API Query Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use `Content.generateDocument` with an `DocumentApiQuery` for more complex fetching. This allows specifying product IDs, display attributes, and additional filters. Handle potential errors during the fetch. ```swift import SyneriseSDK func loadDocumentWithContext(slug: String, productId: String) { let query = DocumentApiQuery(slug: slug) query.productId = productId query.itemsIds = ["ITEM001", "ITEM002"] query.displayAttribute = ["title", "description", "image_url"] query.additionalFilters = "status:active" query.filtersJoiner = .and query.includeContextItems = true Content.generateDocument( apiQuery: query, success: { document in let content = document.content ?? [:] print("Dynamic content for product \(productId): \(content)") }, failure: { error in print("Document query error: \(error.localizedDescription)") } ) } ``` -------------------------------- ### Standard and Conditional Email/Password Sign-In Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use `signIn` for standard authentication. `signInConditionally` handles multi-factor authentication, terms acceptance, and other conditional flows before granting full access. ```swift import SyneriseSDK // Standard sign-in func signIn(email: String, password: String) { Client.signIn( email: email, password: password, success: { print("Signed in — UUID: \(Client.getUUID())") Client.retrieveToken( success: { token in print("Token: \(token.tokenString)") print("Origin: \(token.origin)") print("Expires: \(token.expirationDate)") }, failure: { err in print("Token retrieval failed: \(err.localizedDescription)") } ) }, failure: { error in print("Sign-in failed: \(error.localizedDescription)") } ) } // Conditional sign-in (handles MFA, terms, etc.) func signInConditionally(email: String, password: String) { Client.signInConditionally( email: email, password: password, success: { result in switch result.status { case .success: print("Fully authenticated") case .mfaRequired: print("MFA required — present MFA screen") case .termsAcceptanceRequired: print("Terms acceptance required") case .activationRequired: print("Account not yet activated") default: print("Auth status: \(result.status)") } }, failure: { err in print("Conditional sign-in failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Sign Out Options Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Provides methods for signing out the current user. `signOut()` performs a local sign-out, while `signOut(mode:fromAllDevices:success:failure:)` allows for session destruction and optional sign-out from all devices. ```swift // Sign out options func signOutCurrentDevice() { Client.signOut() // simple local sign-out } func signOutWithMode() { Client.signOut( mode: .signOutWithSessionDestroy, fromAllDevices: false, success: { print("Signed out and session destroyed") }, failure: { err in print("Sign-out error: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Content.getRecommendationsV2 Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Fetches AI-personalized product or content recommendations for the current client, scoped to a campaign slug. Supports context items, filter rules, and display attribute selection. ```APIDOC ## `Content.getRecommendationsV2` — Personalized Recommendations ### Description Fetches AI-personalized product or content recommendations for the current client, scoped to a campaign slug. Supports context items, filter rules, and display attribute selection. ### Method Signature ```swift Content.getRecommendationsV2( options: RecommendationOptions, success: @escaping (_ response: RecommendationResponse) -> Void, failure: @escaping (_ error: Error) -> Void ) ``` ### Parameters #### `options` (RecommendationOptions) An object containing configuration for the recommendation request. - `slug` (String) - Required - The campaign slug to scope recommendations. - `productID` (String?) - Optional - The current product ID. - `productIDs` ([String]?) - Optional - A list of product IDs to consider. - `itemsExcluded` ([String]?) - Optional - A list of item IDs to exclude. - `additionalFilters` (String?) - Optional - Additional filters to apply. - `filtersJoiner` (FiltersJoiner?) - Optional - The joiner for filters (.and or .or). - `displayAttribute` ([String]?) - Optional - Attributes to include in the response. - `includeContextItems` (Bool?) - Optional - Whether to include context items. #### `success` (@escaping (_ response: RecommendationResponse) -> Void) A callback function executed upon successful retrieval of recommendations. #### `failure` (@escaping (_ error: Error) -> Void) A callback function executed if the recommendation request fails. ### Response #### Success Response (`RecommendationResponse`) - `name` (String) - The name of the campaign. - `campaignHash` (String) - The hash of the campaign. - `correlationID` (String) - The correlation ID for tracking. - `items` ([RecommendationItem]) - A list of recommended items. - `itemID` (String) - The ID of the recommended item. - `getAttributeSetForKey` (String) -> Any? - Method to retrieve item attributes. ### Example Usage ```swift let options = RecommendationOptions(slug: "your_campaign_slug") options.productID = "current_product_123" options.displayAttribute = ["name", "price", "image_url"] Content.getRecommendationsV2( options: options, success: { response in // Handle successful response print("Received \(response.items.count) recommendations.") }, failure: { error in // Handle error print("Error fetching recommendations: \(error.localizedDescription)") } ) ``` ``` -------------------------------- ### Import Synerise SDK Source: https://github.com/synerise/synerise-ios-sdk/blob/master/README.md Import the Synerise SDK header file into your Swift or Objective-C files to begin using its functionalities. ```swift import SyneriseSDK ``` ```objective-c #import ``` -------------------------------- ### Retrieve Promotions - Swift Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Fetches a paginated list of promotions. Supports filtering by status, type, and other criteria using `PromotionsApiQuery`. Includes options to include voucher data and metadata. Requires `SyneriseSDK` import. ```swift import SyneriseSDK func loadPromotions() { // Simple fetch — all promotions Promotions.getPromotions( success: { response in let meta = response.metadata print("Total: \(meta?.totalCount ?? 0), Page: \(meta?.page ?? 1)/\(meta?.totalPages ?? 1)") for promo in response.items { print("[\(promo.status)] \(promo.name) — \(promo.discountType) \(promo.discountValue)") } }, failure: { error in print("Promotions error: \(error.localizedDescription)") } ) } func loadFilteredPromotions() { let query = PromotionsApiQuery() query.statuses = [PromotionStatusString.active, PromotionStatusString.assigned] query.types = [PromotionTypeString.membersOnly] query.presentOnly = true // only currently active (date-constrained) query.includeVouchers = true // include voucher data in each Promotion query.includeMeta = true query.limit = 20 query.page = 1 query.checkGlobalActivationLimits = true query.sorting = [[PromotionSortingKey.priority: SyneriseApiQuerySortingOrderString.desc]] Promotions.getPromotions( apiQuery: query, success: { response in for promo in response.items { print("Promo: \(promo.uuid) — \(promo.name)") if let vouchers = promo.vouchers { vouchers.forEach { print(" Voucher: \($0.code) [\($0.status)]") } } } }, failure: { err in print("Filtered promotions error: \(err.localizedDescription)") } ) } // Fetch a single promotion func getPromotion(uuid: String) { Promotions.getPromotion( uuid: uuid, success: { promo in print("Promo: \(promo.name)") print("Discount: \(promo.discountType) \(promo.discountValue)") print("Expires: \(promo.expireAt?.description ?? "never")") }, failure: { err in print("Get promotion failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Fetch Personalized Screen View - Swift Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Fetches a personalized screen view configuration using a feed slug. Requires the `SyneriseSDK` import. Handles success by printing screen details and failure by printing the error description. ```swift import SyneriseSDK func loadPersonalizedScreen(feedSlug: String) { let query = ScreenViewApiQuery(feedSlug: feedSlug) query.productID = "PROD_ABC" query.params = ["platform": "ios", "version": "2.0"] Content.generateScreenView( apiQuery: query, success: { screenView in print("Screen: \(screenView.name) [\(screenView.identifier)]") print("Priority: \(screenView.priority)") print("Path: \(screenView.path)") if let audience = screenView.audience { print("Segments: \(audience.segments ?? [])") } if let data = screenView.data { print("Layout data: \(data)") } }, failure: { error in print("ScreenView error: \(error.localizedDescription)") } ) } ``` -------------------------------- ### Client.registerForPush Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Registers the device push token with the Synerise platform. ```APIDOC ## `Client.registerForPush` ### Description Registers the device's push notification token with the Synerise platform. This should be called after obtaining the APNs device token. ### Method `Client.registerForPush` ### Parameters - **registrationToken** (string) - Required - The device's push notification token. - **mobilePushAgreement** (boolean) - Required - A flag indicating whether to set the user's mobile push marketing consent to true. ### Success Response Indicates that the push token was registered successfully. ### Failure Response Returns an error object if the push token registration fails. ``` -------------------------------- ### Promotions.getPromotions Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Retrieves a paginated list of available promotions for the authenticated client, with optional filtering by status, type, and sorting. ```APIDOC ## `Promotions.getPromotions` — Loyalty Promotions Retrieves a paginated list of available promotions for the authenticated client, with optional filtering by status, type, and sorting. ```swift import SyneriseSDK func loadPromotions() { // Simple fetch — all promotions Promotions.getPromotions( success: { response in let meta = response.metadata print("Total: \(meta?.totalCount ?? 0), Page: \(meta?.page ?? 1)/\(meta?.totalPages ?? 1)") for promo in response.items { print("[\(promo.status)] \(promo.name) — \(promo.discountType) \(promo.discountValue)") } }, failure: { error in print("Promotions error: \(error.localizedDescription)") } ) } func loadFilteredPromotions() { let query = PromotionsApiQuery() query.statuses = [PromotionStatusString.active, PromotionStatusString.assigned] query.types = [PromotionTypeString.membersOnly] query.presentOnly = true // only currently active (date-constrained) query.includeVouchers = true // include voucher data in each Promotion query.includeMeta = true query.limit = 20 query.page = 1 query.checkGlobalActivationLimits = true query.sorting = [[PromotionSortingKey.priority: SyneriseApiQuerySortingOrderString.desc]] Promotions.getPromotions( apiQuery: query, success: { response in for promo in response.items { print("Promo: \(promo.uuid) — \(promo.name)") if let vouchers = promo.vouchers { vouchers.forEach { print(" Voucher: \($0.code) [\($0.status)]") } } } }, failure: { err in print("Filtered promotions error: \(err.localizedDescription)") } ) } // Fetch a single promotion func getPromotion(uuid: String) { Promotions.getPromotion( uuid: uuid, success: { promo in print("Promo: \(promo.name)") print("Discount: \(promo.discountType) \(promo.discountValue)") print("Expires: \(promo.expireAt?.description ?? "never")") }, failure: { err in print("Get promotion failed: \(err.localizedDescription)") } ) } ``` ``` -------------------------------- ### Activate Promotion by UUID Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Activates a promotion using its unique identifier. Provides feedback on success or failure. ```swift import SyneriseSDK func activatePromotion(uuid: String) { Promotions.activatePromotion( uuid: uuid, success: { print("Promotion \(uuid) activated") }, failure: { err in print("Activation failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Confirm Account Activation via Token Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Confirm a user's account activation using a token received via email. Requires SyneriseSDK import. ```swift // Confirm activation with token from email link func confirmActivation(token: String) { Client.confirmAccountActivation( token: token, success: { print("Account activated") }, failure: { err in print("Activation failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Configure Synerise SDK Settings Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Adjust global SDK settings at runtime for various modules like SDK, notifications, tracker, in-app messaging, and injector. Ensure necessary imports are included. ```swift import SyneriseSDK func configureSDKSettings() { let settings = Synerise.settings // General / SDK settings settings.sdk.doNotTrack = false // opt-out of all tracking settings.sdk.minTokenRefreshInterval = 3600 // seconds settings.sdk.shouldDestroySessionOnApiKeyChange = true settings.sdk.appGroupIdentifier = "group.com.myapp" // App Group for extensions settings.sdk.keychainGroupIdentifier = "com.myapp" settings.sdk.SSLPinningPinset = ["BASE64_PUBLIC_KEY_HASH"] // Notifications settings.notifications.enabled = true settings.notifications.disableInAppAlerts = false settings.notifications.encryption = true // payload encryption // Tracker / event batching settings.tracker.minBatchSize = 10 settings.tracker.maxBatchSize = 100 settings.tracker.autoFlushTimeout = 5.0 // seconds settings.tracker.locationAutomatic = false settings.tracker.autoTracking.enabled = true settings.tracker.autoTracking.mode = .fine // In-App Messaging settings.inAppMessaging.checkGlobalControlGroupsOnDefinitionsFetch = true settings.inAppMessaging.maxDefinitionUpdateIntervalLimit = 300 // seconds settings.inAppMessaging.renderingTimeout = 3.0 // Injector (legacy in-app) settings.injector.automatic = true // Custom localizable strings for SDK UI settings.sdk.localizable = [ "SNR_OK": "Confirm", "SNR_CANCEL": "Dismiss" ] } ``` -------------------------------- ### Synerise.settings — Global SDK Configuration Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Configure various aspects of the Synerise SDK at runtime without re-initialization. This includes general SDK settings, notification preferences, tracker behavior, in-app messaging options, and custom localizable strings. ```APIDOC ## `Synerise.settings` — Global SDK Configuration `Synerise.settings` is a `Settings` object that exposes sub-objects (`sdk`, `notifications`, `tracker`, `inAppMessaging`, `injector`) for runtime tuning without requiring re-initialization. ```swift import SyneriseSDK func configureSDKSettings() { let settings = Synerise.settings // General / SDK settings settings.sdk.doNotTrack = false // opt-out of all tracking settings.sdk.minTokenRefreshInterval = 3600 // seconds settings.sdk.shouldDestroySessionOnApiKeyChange = true settings.sdk.appGroupIdentifier = "group.com.myapp" // App Group for extensions settings.sdk.keychainGroupIdentifier = "com.myapp" settings.sdk.SSLPinningPinset = ["BASE64_PUBLIC_KEY_HASH"] // Notifications settings.notifications.enabled = true settings.notifications.disableInAppAlerts = false settings.notifications.encryption = true // payload encryption // Tracker / event batching settings.tracker.minBatchSize = 10 settings.tracker.maxBatchSize = 100 settings.tracker.autoFlushTimeout = 5.0 // seconds settings.tracker.locationAutomatic = false settings.tracker.autoTracking.enabled = true settings.tracker.autoTracking.mode = .fine // In-App Messaging settings.inAppMessaging.checkGlobalControlGroupsOnDefinitionsFetch = true settings.inAppMessaging.maxDefinitionUpdateIntervalLimit = 300 // seconds settings.inAppMessaging.renderingTimeout = 3.0 // Injector (legacy in-app) settings.injector.automatic = true // Custom localizable strings for SDK UI settings.sdk.localizable = [ "SNR_OK": "Confirm", "SNR_CANCEL": "Dismiss" ] } ``` ``` -------------------------------- ### Fetch Dynamic Document by Slug Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use `Content.generateDocument` with a slug to fetch personalized documents. The response contains structured content that can be parsed for display. Ensure to handle potential nil content. ```swift import SyneriseSDK func loadHeroBanner(slug: String) { // Simple slug-based fetch Content.generateDocument( slug: slug, success: { document in print("UUID: \(document.uuid)") print("Schema: \(document.schema)") guard let content = document.content else { return } let title = content["title"] as? String ?? "" let imageUrl = content["image_url"] as? String ?? "" let ctaText = content["cta"] as? String ?? "" print("Banner — Title: \(title), CTA: \(ctaText), Image: \(imageUrl)") }, failure: { error in print("Document error: \(error.localizedDescription)") } ) } ``` -------------------------------- ### Track Custom Event with Metadata Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Tracks a custom event with a specified action and arbitrary metadata provided as a dictionary. ```swift func trackCustomEvent(action: String, metadata: [String: Any] = [:]) { let params = TrackerParams.make { builder in for (key, value) in metadata { builder.setObject(value, forKey: key) } } let event = CustomEvent(label: "custom.event", action: action, params: params) Tracker.send(event) } ``` -------------------------------- ### Synerise.changeApiKey — Runtime API Key Switching Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Switches the SDK to a different workspace at runtime without requiring app restart. Useful for multi-tenant applications or A/B workspace testing. ```APIDOC ## Synerise.changeApiKey — Runtime API Key Switching ### Description Switches the SDK to a different workspace at runtime without requiring app restart. Useful for multi-tenant applications or A/B workspace testing. ### Method (Not applicable for SDK method) ### Endpoint (Not applicable for SDK method) ### Parameters #### SDK Method Parameters - **newApiKey** (String) - Required - The new API key for the target workspace. - **config** (InitializationConfig) - Optional - Configuration object for the new API key, can include `requestValidationSalt`. ### Request Example ```swift let config = InitializationConfig() config.requestValidationSalt = "optional_salt" Synerise.changeApiKey("new_api_key", config: config) ``` ## Synerise.setRequestValidationSalt — Update Request Validation Salt ### Description Updates the request validation salt for the SDK at runtime. ### Method (Not applicable for SDK method) ### Endpoint (Not applicable for SDK method) ### Parameters #### SDK Method Parameters - **salt** (String) - Required - The new salt value to set. ### Request Example ```swift Synerise.setRequestValidationSalt("new_salt_value") ``` ### Response (No specific response body detailed, changes are applied internally) ``` -------------------------------- ### Configure Tracker with Custom Identifiers Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Sets custom identifiers, such as a loyalty card number or email, on the tracker for user identification. ```swift func configureTracker() { Tracker.setCustomIdentifier("loyalty_card_12345") Tracker.setCustomEmail("loyalty@example.com") } ``` -------------------------------- ### Activate Multiple Promotions Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Activates multiple promotions in a batch, identified by UUIDs or codes. Useful for bulk operations. ```swift func activateMultiple(uuids: [String], codes: [String]) { var identifiers: [PromotionIdentifier] = uuids.map { .init(uuid: $0) } identifiers += codes.map { .init(code: $0) } Promotions.activatePromotions( identifiers: identifiers, success: { print("Batch activation complete") }, failure: { err in print("Batch activation failed: \(err.localizedDescription)") } ) } ``` -------------------------------- ### Track Product Viewed Event Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Tracks a product view event with details like product ID, name, category, URL, and recommendation status. ```swift func trackProductViewed(productId: String, productName: String) { let event = ProductViewedEvent(label: "product.viewed", productName: productName, productId: productId) event.setCategory("Electronics") event.setURL(URL(string: "https://store.example.com/products/\(productId)")!) event.setIsRecommended(true) Tracker.send(event) } ``` -------------------------------- ### Fetch Brickworks Content - Swift Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Retrieves structured content from Synerise Brickworks using a schema slug and record slug. Requires `SyneriseSDK` import. The success callback prints the content dictionary and a specific headline if available. Handles errors by printing descriptions. ```swift import SyneriseSDK func loadBrickworksContent(schemaSlug: String, recordSlug: String) { let query = BrickworksApiQuery(schemaSlug: schemaSlug, recordSlug: recordSlug) query.context = ["user_segment": "premium", "locale": "en_US"] query.fieldContext = ["currency": "USD"] Content.generateBrickworks( apiQuery: query, success: { contentDict in print("Brickworks content: \(contentDict)") if let headline = contentDict["headline"] as? String { print("Headline: \(headline)") } }, failure: { error in print("Brickworks error: \(error.localizedDescription)") } ) } ``` -------------------------------- ### Custom and Screen View Events Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Send custom events with arbitrary metadata and track screen views. ```APIDOC ## `Tracker.send` — Custom and Screen View Events ### Description Allows for flexible event tracking with custom data and tracking user navigation through screens. ### Methods - `trackCustomEvent(action: String, metadata: [String: Any])`: Sends a custom event with a specified action and metadata. - `trackScreenVisited(screenName: String)`: Sends an event when a user visits a specific screen. ### Usage Examples ```swift // Track a custom event let customMetadata = ["contentType": "article", "contentId": "12345"] Tracker.send(CustomEvent(label: "custom.event", action: "article.viewed", params: TrackerParams.make { builder in for (key, value) in customMetadata { builder.setObject(value, forKey: key) } })) // Track screen visit let screenParams = TrackerParams.make { builder in builder.setString("HomePage", forKey: "screen") } Tracker.send(VisitedScreenEvent(label: "screen.visited", params: screenParams)) ``` ``` -------------------------------- ### Content.generateScreenView Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Fetches a personalized screen view configuration for a given feed slug, enabling server-driven UI layouts and targeting. ```APIDOC ## `Content.generateScreenView` — Screen Personalization Fetches a personalized screen view configuration for a given feed slug, enabling server-driven UI layouts and targeting. ```swift import SyneriseSDK func loadPersonalizedScreen(feedSlug: String) { let query = ScreenViewApiQuery(feedSlug: feedSlug) query.productID = "PROD_ABC" query.params = ["platform": "ios", "version": "2.0"] Content.generateScreenView( apiQuery: query, success: { screenView in print("Screen: \(screenView.name) [\(screenView.identifier)]") print("Priority: \(screenView.priority)") print("Path: \(screenView.path)") if let audience = screenView.audience { print("Segments: \(audience.segments ?? [])") } if let data = screenView.data { print("Layout data: \(data)") } }, failure: { error in print("ScreenView error: \(error.localizedDescription)") } ) } ``` ``` -------------------------------- ### Fetch and Update Client Profile Source: https://context7.com/synerise/synerise-ios-sdk/llms.txt Use `Client.getAccount` to retrieve the full authenticated client profile. `Client.updateAccount` allows updating specific profile fields like name, phone, and agreements. ```swift import SyneriseSDK func fetchAndUpdateProfile() { // Fetch full profile Client.getAccount( success: { account in print("Client ID: \(account.clientId)") print("Email: \(account.email)") print("Name: \(account.firstName ?? "") \(account.lastName ?? "")") print("UUID: \(account.uuid)") print("Tags: \(account.tags ?? [])") print("Anonymous: \(account.anonymous)") print("Email consent: \(account.agreements.email)") }, failure: { err in print("Get account failed: \(err.localizedDescription)") } ) } ``` ```swift func updateProfile() { let context = ClientUpdateAccountContext() context.firstName = "Jane" context.lastName = "Smith" context.phone = "+48600000001" context.city = "Kraków" context.countryCode = "PL" context.birthDate = "1988-03-22" let agreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true context.agreements = agreements context.attributes = ["preferred_lang": "pl", "vip": true] Client.updateAccount( context: context, success: { print("Profile updated") }, failure: { err in print("Update failed: \(err.localizedDescription)") } ) } ```