# Segmentify iOS SDK
> Send events and show recommendations, search results and push notifications in your iOS app with the Segmentify iOS SDK.
import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';
## What the SDK does
Page and product views, basket and checkout steps, wishlist, search and
user events, each with one method call.
Event methods hand back the recommendation widgets set up in your
Segmentify panel, ready for you to render.
Instant search and faceted search results, with click tracking.
Registers device tokens and reports views and clicks of push campaigns.
## Start here
## Related documentation
---
# Installation
> Add the Segmentify iOS SDK to your project.
The Segmentify iOS SDK supports **iOS 13** and higher.
## Add the SDK
**Swift Package Manager** (recommended). In Xcode choose **File > Add Package Dependencies**, enter the repository URL and add the `Segmentify` library to your app target:
```text
https://github.com/segmentify/ios-sdk
```
Or add it to a `Package.swift`:
```swift
dependencies: [
.package(url: "https://github.com/segmentify/ios-sdk", from: "1.7.0")
]
```
**CocoaPods** (legacy). Add the pod to your `Podfile` and run `pod install`:
```ruby
pod "Segmentify"
```
Then import the module where you use it:
```swift
import Segmentify
```
## What you need from Segmentify
Have these ready before you configure the SDK. The API key and data center are under **Settings > Integrations** in the Segmentify panel.
| You need | Example | Used for |
| --- | --- | --- |
| API key | `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` | Identifies your account. |
| Data center URL | `https://gandalf-eu.segmentify.com` | The host your account lives on. |
| Domain | `www.yourdomain.com` | The domain registered for your account. The SDK sends it with every request. |
| Push data center URL | `https://gimli-eu.segmentify.com` | Only if you use push notifications. |
Data centers by region:
| Region | Data center URL | Push data center URL |
| --- | --- | --- |
| Türkiye | `https://per2.segmentify.com` | `https://psh2.segmentify.com` |
| Europe | `https://gandalf-eu.segmentify.com` | `https://gimli-eu.segmentify.com` |
| Latin America | `https://gandalf-br.segmentify.com` | `https://gimli-br.segmentify.com` |
Use the one shown in your panel. An API key sent to another data center is not found.
Next: [Configuration](/getting-started/configuration/).
---
# Configuration
> Initialise the Segmentify iOS SDK, and set session length, logging and the fields every event shares.
## Initialise the SDK
Configure the SDK once, when the app starts, before sending any event.
```swift
import Segmentify
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
SegmentifyManager.config(
appkey: "YOUR_API_KEY",
dataCenterUrl: "https://gandalf-eu.segmentify.com", // your data center URL
subDomain: "www.yourdomain.com" // the domain registered for your account
)
return true
}
}
```
After `config`, use the shared instance for every event: `SegmentifyManager.sharedManager()`.
| Parameter | Description |
| --- | --- |
| API key | Your Segmentify API key. |
| Data center URL | The full URL of your data center, starting with `https://`. |
| Domain | The domain registered for your Segmentify account. It is sent as the `Origin` of every request and must match the account, or requests are rejected. |
- Call `config` before the first `sharedManager()`. Without an API key the SDK prints an error and events are not sent.
- Logging is on by default. Turn it off for release builds.
## Options
```swift
_ = SegmentifyManager.setSessionKeepSecond(sessionKeepSecond: 86400) // session length in seconds; 86400 is the default
_ = SegmentifyManager.logStatus(isVisible: false) // SDK logs in the Xcode console; on by default
```
| Option | Default | Description |
| --- | --- | --- |
| Session length | `86400` seconds (24 hours) | How long a session ID is kept before a new one is created. |
| Logging | on | Prints what the SDK does, including why an event was not sent. |
## User and session IDs
You do not create user or session IDs. On first launch the SDK asks Segmentify for a user ID and a session ID and stores them in `UserDefaults`. The user ID is kept; the session ID is replaced when the session length has passed.
## Fields every event shares
Every event model has these properties. Set them on each event you send.
```swift
let page = PageModel()
page.category = "Home Page"
page.lang = "EN"
page.currency = "EUR"
page.testMode = true // remove before going live
page.params = ["campaign": "summer" as AnyObject] // optional custom values
```
| Property | Description |
| --- | --- |
| `lang` | Language of the content, for example `EN`. Must be a language configured for your account. Set it on every event: when it is missing, `EN` is assumed, and accounts without English get no result. |
| `currency` | Currency of the prices, for example `EUR`. Must be a currency configured for your account. |
| `region` | Region of the user, if your account uses regions. |
| `params` | Custom key-value pairs to send with the event. |
| `testMode` | `true` marks a test event. Test events are answered by test-mode campaigns and kept apart from live data. |
| `pageUrl` | URL or deep link of the screen. |
## Switching account at runtime
If one app serves several Segmentify accounts (for example one per country), change the configuration when the user switches:
```swift
SegmentifyManager.setConfig(apiKey: "OTHER_API_KEY", dataCenterUrl: "https://gandalf-eu.segmentify.com", subDomain: "www.otherdomain.com")
```
Next: [Your first integration](/getting-started/first-integration/).
---
# Your first integration
> A screen-by-screen plan for a first Segmentify iOS SDK integration, with a checklist for going live.
This page is the order to build things in. Each step links to the page with the code.
## How it works
Your app tells Segmentify what the user does by calling one SDK method per action. Segmentify answers some of those calls with **recommendations**: lists of products to show on that screen, as set up in your Segmentify panel. So the same calls both collect data and fetch content.
Methods that can return recommendations take a closure. Methods that only record something (basket changes, clicks, user events) return nothing.
## Step 1: Install and configure
1. [Install the SDK](/getting-started/installation/).
2. [Configure it](/getting-started/configuration/) at app start with your API key, data center URL and domain.
3. Turn on logs while you develop.
## Step 2: Send a page view from every screen
Call `sendPageView` when a screen opens, with the screen's `category`. This is the minimum integration: it identifies visitors and lets campaigns target screens.
```swift
let page = PageModel()
page.category = "Home Page"
page.lang = "EN"
page.currency = "EUR"
SegmentifyManager.sharedManager().sendPageView(segmentifyObject: page) { recommendations in
// recommendations holds the widgets to show on this screen
}
```
See [Page View](/events/page-view/) for the category names.
## Step 3: Add the shopping events
| When | Call | Page |
| --- | --- | --- |
| A product screen opens | `sendProductView` (and `sendPageView` with `Product Page`) | [Product View](/events/product-view/) |
| A product is added to or removed from the basket | `sendAddOrRemoveBasket` | [Basket and Checkout](/events/basket-and-checkout/) |
| The basket screen opens | `sendViewBasket` | [Basket and Checkout](/events/basket-and-checkout/) |
| An order is completed | `sendPurchase` | [Basket and Checkout](/events/basket-and-checkout/) |
These four are what recommendations and revenue reports are built on. Get them right before adding anything else.
## Step 4: Show recommendations
Render the recommendations returned to your callbacks, and report when a widget is shown and when a product in it is tapped. See [Recommendations](/recommendations/).
## Step 5: Add what your app needs
| Feature | Page |
| --- | --- |
| Sign-up, sign-in, profile and consent | [User Events](/events/user/) |
| Wishlist | [Wishlist](/events/wishlist/) |
| Search | [Search](/events/search/) |
| Banners | [Interactions and Banners](/events/interactions/) |
| Your own triggers | [Custom Event](/events/custom-event/) |
| Push notifications | [Push Notifications](/push-notifications/) |
## Go-live checklist
- `testMode` is removed, or `false`, on every event.
- `lang` and `currency` are set on every event and match your account.
- `sendProductView` sends the real price, stock status, product URL and image.
- `sendPurchase` is called once per order, with `orderNo`.
- Product IDs are the same ones as in your product catalogue and on your website.
- Logging is off in release builds.
If an event does not arrive, see [Troubleshooting](/troubleshooting/).
---
# Basket and Checkout
> Report basket changes and the steps of the checkout funnel, from viewing the basket to a completed order.
## Basket changes
Call `sendAddOrRemoveBasket` when a product is added to or removed from the basket.
```swift
let basket = BasketModel()
basket.step = "add" // or "remove"
basket.productId = "SKU-1001"
basket.quantity = 1
basket.price = 135.0
basket.lang = "EN"
basket.currency = "EUR"
SegmentifyManager.sharedManager().sendAddOrRemoveBasket(segmentifyObject: basket)
```
A shorter form takes the values directly:
```swift
SegmentifyManager.sharedManager().sendAddOrRemoveBasket(basketStep: "add", productID: "SKU-1001", quantity: 1, price: 135.0)
```
| Property | Required | Description |
| --- | --- | --- |
| `step` | Yes | `add` or `remove`. |
| `productId` | Yes | The product. |
| `quantity` | Yes | How many were added or removed. |
| `price` | Recommended | Unit price. |
Without `step`, `productId` or `quantity` the event is not sent.
## Checkout steps
The checkout methods all take the basket's total and its products.
```swift
let checkout = CheckoutModel()
checkout.totalPrice = 135.0
checkout.productList = [
["productId": "SKU-1001", "quantity": 1, "price": 135.0]
]
checkout.lang = "EN"
checkout.currency = "EUR"
```
Each item of `productList` is a dictionary with `productId`, `quantity` and `price`.
Then call the method for the step the user is on:
```swift
let manager = SegmentifyManager.sharedManager()
manager.sendViewBasket(segmentifyObject: checkout) { recommendations in } // basket screen
manager.sendCustomerInformation(segmentifyObject: checkout) { recommendations in } // address / customer step
manager.sendPaymentInformation(segmentifyObject: checkout) { recommendations in } // payment step
checkout.orderNo = "ORDER-98765"
manager.sendPurchase(segmentifyObject: checkout) { recommendations in } // order completed
```
| Method | When |
| --- | --- |
| `sendViewBasket` | The basket screen opens. |
| `sendCustomerInformation` | The user is on the customer or address step. |
| `sendPaymentInformation` | The user is on the payment step. |
| `sendPurchase` | The order is completed. |
| Property | Required | Description |
| --- | --- | --- |
| `totalPrice` | Yes | Total of the basket or order. |
| `productList` | Yes | The products, each with `productId`, `quantity` and `price`. |
| `orderNo` | For purchase | Your order number. |
## Rules
- Call `sendPurchase` **once per order**. Calling it again on a screen refresh counts the revenue twice.
- `totalPrice` and the product prices are in the currency named by `currency`.
- All four methods return recommendations to their callback, for example "you may also like" on the basket screen.
---
# Custom Event
> Send an event of your own to trigger Segmentify campaigns.
Use a custom event for anything the standard events do not cover, such as a newsletter sign-up or a store-locator search. Campaigns in the panel can be triggered by its `type`.
```swift
let event = CustomEventModel()
event.type = "newsletter-signup"
event.params = ["source": "footer" as AnyObject]
event.lang = "EN"
SegmentifyManager.sharedManager().sendCustomEvent(segmentifyObject: event) { recommendations in }
// or, with the values passed directly
SegmentifyManager.sharedManager().sendCustomEvent(type: "newsletter-signup", params: nil, lang: "EN") { recommendations in }
```
| Property | Required | Description |
| --- | --- | --- |
| `type` | Yes | Your name for the event. Must match the name used in the panel. |
| `params` | No | Extra values to send with the event. |
The callback receives recommendations if a campaign answers the event.
---
# Interactions and Banners
> Report when a recommendation widget is shown, seen and clicked, and track banners.
Segmentify measures a campaign by its interactions. Without them, widgets show up in your app but their reports stay empty.
## Widget interactions
```swift
let manager = SegmentifyManager.sharedManager()
// the widget was returned and placed on the screen
manager.sendImpression(instanceId: instanceId, interactionId: interactionId)
// the widget became visible to the user
manager.sendWidgetView(instanceId: instanceId, interactionId: interactionId)
// the user tapped a product of the widget
manager.sendClickView(instanceId: instanceId, interactionId: productId)
```
| Method | When | `interactionId` |
| --- | --- | --- |
| `sendImpression` | The widget was returned and placed on the screen. | The `interactionId` of the recommendation. |
| `sendWidgetView` | The widget scrolled into view. | The `interactionId` of the recommendation. |
| `sendClickView` | The user tapped a product in the widget. | The product ID. |
| `sendSearchClickView` | The user tapped a product in search results. | The product ID. |
`instanceId` is always the ID of the campaign, taken from the recommendation or search response.
Send an impression once per widget per screen load, not on every scroll.
## Banners
If you use Segmentify's banner tracking, report the banners your app shows and the taps on them.
```swift
let banner = BannerOperationsModel()
banner.group = "Home Page Slider"
banner.title = "Summer Sale"
banner.order = 1
let manager = SegmentifyManager.sharedManager()
manager.sendBannerImpressionEvent(segmentifyObject: banner)
manager.sendBannerClickEvent(segmentifyObject: banner)
let slide = InternalBannerModel()
slide.title = "Summer Sale"
slide.image = "https://cdn.yourdomain.com/banners/summer.jpg"
slide.order = 1
slide.urls = ["https://www.yourdomain.com/summer"]
let group = BannerGroupViewModel()
group.group = "Home Page Slider"
group.banners = [slide]
manager.sendBannerGroupViewEvent(segmentifyObject: group)
```
| Method | When |
| --- | --- |
| `sendBannerGroupViewEvent` | A banner group (for example a slider) is shown, with the banners in it. |
| `sendBannerImpressionEvent` | One banner became visible. |
| `sendBannerClickEvent` | The user tapped a banner. |
| `sendBannerUpdateEvent` | A banner's content changed. |
`group` is the name of the banner area and must be the same in every event for that area.
---
# Page View
> Report every screen the user opens with sendPageView, and receive the recommendations for that screen.
Send a page view each time a screen opens. The `category` says what kind of screen it is.
```swift
let page = PageModel()
page.category = "Home Page"
page.lang = "EN"
page.currency = "EUR"
SegmentifyManager.sharedManager().sendPageView(segmentifyObject: page) { recommendations in
// recommendations holds the widgets to show on this screen
}
```
## Categories
Use these names for the standard screens. They are what campaigns in the panel target.
| `category` | Screen |
| --- | --- |
| `Home Page` | Home screen |
| `Category Page` | A product listing. Also set `subCategory`. |
| `Product Page` | A product's detail screen. Also send [Product View](/events/product-view/). |
| `Search Page` | Search results |
| `Basket Page` | Basket |
| `Checkout Success Page` | Order confirmation |
| `404 Page` | Content not found |
For any other screen, use your own name, for example `Account Page`.
## Category screens
```swift
let page = PageModel()
page.category = "Category Page"
page.subCategory = "Shoes > Sneakers"
page.lang = "EN"
page.currency = "EUR"
SegmentifyManager.sharedManager().sendPageView(segmentifyObject: page) { recommendations in }
```
## Properties
| Property | Required | Description |
| --- | --- | --- |
| `category` | Yes | The screen type. Without it the event is not sent. |
| `subCategory` | No | The category shown on a category screen. |
| `recommendIds` | No | IDs of the recommendation campaigns already shown on the screen. |
Plus the [shared fields](/getting-started/configuration/#fields-every-event-shares).
## The result
The callback receives a list of recommendation widgets for the screen. It is empty when no campaign targets it. See [Recommendations](/recommendations/).
---
# Product View
> Report a product detail screen with sendProductView. Keeps the product catalogue current and returns product-page recommendations.
Send a product view when a product's detail screen opens. It does two jobs: it records the user's interest, and it updates the product (price, stock, image) in your Segmentify catalogue.
```swift
let product = ProductModel()
product.productId = "SKU-1001"
product.name = "Runner Sneakers"
product.url = "https://www.yourdomain.com/runner-sneakers"
product.image = "https://cdn.yourdomain.com/img/sku-1001.jpg"
product.categories = ["Shoes", "Sneakers"]
product.price = 135.0
product.oldPrice = 160.0
product.brand = "Acme"
product.inStock = true
product.lang = "EN"
product.currency = "EUR"
SegmentifyManager.sharedManager().sendProductView(segmentifyObject: product) { recommendations in
// recommendations for the product screen
}
```
Send a [page view](/events/page-view/) with category `Product Page` for the same screen as well.
## Properties
| Property | Type | Required | Description |
| --- | --- | --- | --- |
| `productId` | `String` | Yes | Your ID of the product. |
| `name` | `String` | Yes | Product name. |
| `url` | `String` | Yes | Product page URL. |
| `image` | `String` | Yes | Main image URL. |
| `price` | `NSNumber` | Yes | Current price. |
| `category` | `String` | One of the two | A single category. |
| `categories` | `[String]` | One of the two | The category path. Set either `category` or `categories`, not both. |
| `oldPrice` | `NSNumber` | No | Price before discount. |
| `brand` | `String` | No | Brand name. |
| `inStock` | `Bool` | No | Whether the product can be bought. |
| `mUrl` | `String` | No | Mobile product page URL. |
| `imageXS`, `imageS`, `imageM`, `imageL`, `imageXL` | `String` | No | Image URLs in other sizes. |
| `gender` | `String` | No | Target gender. |
| `colors`, `sizes`, `labels` | `[String]` | No | Product attributes. |
| `noUpdate` | `Bool` | No | `true` sends the view without updating the product in the catalogue. |
Plus the [shared fields](/getting-started/configuration/#fields-every-event-shares).
## Rules
- The event is **not sent** if `productId`, `name`, `url`, `image` or `price` is missing, if both `category` and `categories` are set, or if neither is. The SDK logs which one.
- `productId` must be the same ID your product feed and website use for the product.
- `oldPrice` is only used when it is greater than `price`.
- Send `currency` with the price.
---
# Search
> Get instant and faceted search results from Segmentify and report clicks on them.
Segmentify Search has two modes. **Instant search** answers while the user types, in the search box. **Faceted search** returns a full results screen with filters, sorting and paging.
## Instant search
Send the current text each time it changes. Send an empty `query` when the search box opens, to get the "before search" content such as popular products and last searches.
```swift
let search = SearchPageModel()
search.query = "sneak" // empty string before the user types
search.lang = "EN"
search.currency = "EUR"
SegmentifyManager.sharedManager().sendSearchPageView(segmentifyObject: search) { response in
// response.products, response.keywords, response.categories, response.brands, response.lastSearches
}
```
The response holds `products`, plus `keywords`, `categories`, `brands`, `categoryProducts`, `brandProducts` and `lastSearches` to build the search box's sections.
## Faceted search
```swift
let search = SearchFacetPageModel()
search.query = "sneakers"
search.type = "faceted"
search.trigger = "keyword" // what caused the search: keyword, filter, order or page
search.ordering = FacetedOrdering(page: 1, sort: "SMART_SORTING")
search.filters = [FacetedFilter(facet: "brand", values: ["Acme"])]
search.lang = "EN"
search.currency = "EUR"
SegmentifyManager.sharedManager().sendFacetedSearchPageView(segmentifyObject: search) { response in
// response.products, response.facets, response.meta, response.banners, response.instanceId
}
```
| Property | Description |
| --- | --- |
| `query` | The text searched. |
| `trigger` | What caused this request: `keyword` (a new search), `filter` (a filter changed), `order` (the sort changed) or `page` (another page). |
| `ordering` | The page number, starting at 1, and the sort. |
| `filters` | The selected filters, each a facet name and its selected values. |
The response holds `products`, `facets` (the available filters and their values), `meta` (paging and totals), `banners` and the `instanceId` of the search campaign.
## Report clicks
When the user taps a product in search results, report it with the search campaign's `instanceId` and the product ID:
```swift
SegmentifyManager.sharedManager().sendSearchClickView(instanceId: instanceId, interactionId: "SKU-1001")
```
Report when the results are shown with `sendImpression` and `sendWidgetView`, as for recommendation widgets. See [Interactions and Banners](/events/interactions/).
## Clear a last search
When the user deletes an entry from their last searches:
```swift
let user = UserModel()
user.lastSearchDeletedKeywords = "sneakers"
SegmentifyManager.sharedManager().sendUserClearLastSearchHistory(segmentifyObject: user)
```
---
# User Events
> Tell Segmentify who the user is: sign-up, sign-in, profile changes, consent and channel subscriptions.
There are two sets of user methods. Use the **CDP user events** in new integrations. The older **user operations** are still supported.
## CDP user events
Each method takes the user's profile.
```swift
let profile: CdpEventsPayload = [
"email": "jane@example.com",
"phone": "905551234567",
"username": "jane",
"fullName": "Jane Doe",
"gender": "female",
"emailConsent": "SUBSCRIBED",
"loyaltyLevel": "gold"
]
let manager = SegmentifyManager.sharedManager()
manager.registerUser(profile) // after sign-up
manager.loginUser(profile) // after sign-in
manager.identifyUser(profile) // when the profile is known or has changed
manager.userTraits(profile) // to update traits
manager.logoutUser(profile) // after sign-out
```
`CdpEventsPayload` is a `[String: Any]` dictionary.
| Key | Type | Description |
| --- | --- | --- |
| `email`, `phone`, `username` | `String` | Identifiers of the user. |
| `fullName`, `gender` | `String` | Profile fields. |
| `source` | `String` | Where the data came from. |
| `emailConsent`, `smsConsent`, `whatsappConsent`, `callConsent` | `String` | `SUBSCRIBED`, `UNSUBSCRIBED` or `NOT_SET`. |
| any other key | `String`, number or `Bool` | Your own attributes. |
| Method | When |
| --- | --- |
| `registerUser` | The user completed sign-up. |
| `loginUser` | The user signed in. |
| `identifyUser` | The app knows who the user is, or the profile changed. Sent only when the profile differs from the last one sent, so it is safe to call often. |
| `userTraits` | To update profile traits. |
| `logoutUser` | The user signed out. |
Behaviour to know:
- An empty profile is not sent.
- If you set at least one consent field, the others are sent as `NOT_SET`. If you set none, no consent is sent and stored consents are left as they are.
## Channel subscriptions
Report when a user subscribes to, or unsubscribes from, a channel.
```swift
let manager = SegmentifyManager.sharedManager()
manager.subscribeUser(.email(email: "jane@example.com", purpose: "MARKETING"))
manager.subscribeUser(.sms(phoneNumber: "905551234567"))
manager.subscribeUser(.whatsapp(phoneNumber: "905551234567"))
manager.subscribeUser(.call(phoneNumber: "905551234567"))
manager.subscribeUser(.iosPush(pushSubscriptionId: fcmToken))
manager.unsubscribeUser(CdpUnsubscribePayload(channel: .email, email: "jane@example.com"))
manager.unsubscribeUser(CdpUnsubscribePayload(channel: .sms, phoneNumber: "905551234567"))
```
## User operations (legacy)
```swift
let user = UserModel()
user.email = "jane@example.com"
user.username = "jane" // your username or user ID
user.fullName = "Jane Doe"
let manager = SegmentifyManager.sharedManager()
manager.sendUserRegister(segmentifyObject: user) // sign-up
manager.sendUserLogin(segmentifyObject: user) // sign-in
manager.sendUserUpdate(segmentifyObject: user) // profile change
manager.sendUserLogout(segmentifyObject: user) // sign-out
```
Do not send both sets for the same action. Pick one per integration.
---
# Wishlist
> Report wishlist additions, removals and views.
```swift
let manager = SegmentifyManager.sharedManager()
manager.sendWishlistAdd(productId: "SKU-1001")
manager.sendWishlistRemove(productId: "SKU-1001")
manager.sendWishlistDetail(productId: "SKU-1001")
manager.sendWishlistViewFavorites(favoritesList: ["SKU-1001", "SKU-2002"])
```
To set `lang`, `currency` or `params`, build a `WishlistModel` and call `sendWishlist`:
```swift
let wishlist = WishlistModel()
wishlist.step = "add" // add, remove, detail or view-favorites
wishlist.productId = "SKU-1001"
wishlist.lang = "EN"
manager.sendWishlist(segmentifyObject: wishlist)
```
| Step | Method | Needs |
| --- | --- | --- |
| `add` | `sendWishlistAdd` | `productId` |
| `remove` | `sendWishlistRemove` | `productId` |
| `detail` | `sendWishlistDetail` | `productId`. The user opened a product from the wishlist. |
| `view-favorites` | `sendWishlistViewFavorites` | `favoritesList`, the product IDs in the wishlist. May be empty. |
The event is not sent when the step is not one of the four, or when the field it needs is missing.
---
# Push Notifications
> Register the device with Segmentify and report views and clicks of push campaigns.
Segmentify sends push campaigns through Firebase Cloud Messaging (FCM) or APNs. Your app receives and displays the notifications; the SDK registers the device and reports what happens to each notification.
## Set up
Set the push data center next to `config`:
```swift
SegmentifyManager.config(appkey: "YOUR_API_KEY", dataCenterUrl: "https://gandalf-eu.segmentify.com", subDomain: "www.yourdomain.com")
SegmentifyManager.setPushConfig(dataCenterUrlPush: "https://gimli-eu.segmentify.com") // your push data center URL
```
Without it the push methods print an error and send nothing.
Enable the **Push Notifications** capability for your target, request the user's permission with `UNUserNotificationCenter`, and call `registerForRemoteNotifications()`. If you deliver through Firebase, add Firebase Messaging as described in the [Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/client). The SDK does not include Firebase.
## Register the device token
Send the token to Segmentify whenever you receive or refresh it.
```swift
// Firebase: MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
guard let fcmToken else { return }
let model = NotificationModel()
model.type = NotificationType.PERMISSION_INFO
model.providerType = ProviderType.FIREBASE // use ProviderType.APNS with a raw APNs token
model.deviceToken = fcmToken
SegmentifyManager.sharedManager().sendNotification(segmentifyObject: model)
}
```
With APNs directly, send the hex string of the device token from `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` and set `providerType` to `.APNS`.
Without a registered token the user cannot be targeted by push campaigns.
## Report views and clicks
Build a `SegmentifyPushPayload` from the incoming message and hand it to the SDK.
```swift
extension AppDelegate: UNUserNotificationCenterDelegate {
// shown while the app is in the foreground
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
let payload = SegmentifyPushPayload(userInfo: notification.request.content.userInfo)
SegmentifyManager.sharedManager().handlePushReceived(payload)
completionHandler([.banner, .sound, .badge])
}
// the user tapped the notification
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let payload = SegmentifyPushPayload(userInfo: response.notification.request.content.userInfo)
SegmentifyManager.sharedManager().handlePushClicked(payload)
if let target = payload.targetUrl, let url = URL(string: target) {
DispatchQueue.main.async { UIApplication.shared.open(url) }
}
completionHandler()
}
}
```
Set the delegate at launch: `UNUserNotificationCenter.current().delegate = self`.
`handlePushReceived` reports a view and `handlePushClicked` reports a click. Both need the payload's `instanceId`; a message without one is not a Segmentify campaign and is ignored.
## The payload
| Property | Type | Description |
| --- | --- | --- |
| `title`, `message` | `String` | Text of the notification. Empty when not sent. |
| `image` | `String?` | Image URL. |
| `deeplink`, `redirectUrl` | `String?` | Where a tap should lead. |
| `targetUrl` | `String?` | `deeplink` if present, otherwise `redirectUrl`. |
| `instanceId` | `String?` | ID of the push campaign. Needed to report views and clicks. |
| `tag` | `String?` | Notification tag. |
| `actions` | `[SegmentifyPushAction]` | Action buttons, each with `action`, `title`, `icon`, `redirectUrl`, `deeplink`. |
| `providerType` | `ProviderType` | `.FIREBASE` or `.APNS`, detected from the message. |
| `isV2` | `Bool` | Whether the message uses the current payload format. |
## Attribute what happens next
After a click, the SDK remembers the campaign so you can attribute the visit that follows:
```swift
let utm = SegmentifyManager.sharedManager().getTrackingParameters()
// utm.utm_source, utm.utm_medium, utm.utm_campaign, utm.utm_content
```
Add these to the deep link or to your own analytics events if you track campaign sources.
## Checklist
- The push data center URL is set.
- The token is sent on first launch and on every refresh.
- Views are reported when a notification arrives, and clicks when it is tapped.
- The notification opens `targetUrl` when one is present.
---
# Recommendations
> Render the recommendation widgets the SDK returns, and report their impressions and clicks.
Event methods with a callback return the recommendation campaigns that apply to the event. Which campaigns, with which products, is set up in your Segmentify panel; the app only renders what comes back.
## What you receive
A list of recommendations, one per campaign. It is empty when no campaign applies.
| Property | Description |
| --- | --- |
| `notificationTitle` | The title of the widget, as set in the panel. |
| `products` | The products to show, in order. |
| `instanceId` | ID of the campaign. Use it when reporting interactions. |
| `interactionId` | ID of this response. Use it as `interactionId` for impressions and widget views. |
| `errorString` | Set when the response could not be read. |
Each product has, among others:
| Property | Description |
| --- | --- |
| `productId` | Your ID of the product. |
| `name` | Product name. |
| `url`, `mUrl` | Product page URLs. |
| `image`, `imageXS` ... `imageXL` | Image URLs. |
| `price`, `oldPrice`, `specialPrice` | Prices as numbers. |
| `priceText`, `oldPriceText`, `specialPriceText` | Prices formatted for display. |
| `brand`, `category`, `categories` | Brand and categories. |
| `inStock`, `stockCount` | Availability. |
| `params` | Custom product fields from your catalogue. |
## Render and report
```swift
SegmentifyManager.sharedManager().sendPageView(segmentifyObject: page) { recommendations in
for recommendation in recommendations {
guard let products = recommendation.products,
let instanceId = recommendation.instanceId,
let interactionId = recommendation.interactionId else { continue }
DispatchQueue.main.async {
self.showWidget(title: recommendation.notificationTitle, products: products) // your own UI code
}
SegmentifyManager.sharedManager().sendImpression(instanceId: instanceId, interactionId: interactionId)
}
}
```
The closure is not guaranteed to run on the main thread. Dispatch to the main queue before touching views.
1. Render each recommendation as a widget: its title and its products.
2. Call `sendImpression` when you place the widget.
3. Call `sendWidgetView` when it becomes visible.
4. Call `sendClickView` with the product ID when a product is tapped.
See [Interactions and Banners](/events/interactions/) for the three calls.
## Where recommendations come from
| Screen | Call that returns them |
| --- | --- |
| Home, category and other screens | `sendPageView` |
| Product | `sendProductView` |
| Basket | `sendViewBasket` |
| Order confirmation | `sendPurchase` |
| Anything else | `sendCustomEvent` |
If you get an empty list, check in the panel that a campaign is active for that page type and that test mode matches: a campaign in test mode only answers events sent with `testMode` on.
---
# Troubleshooting
> What to check when an event is not sent, recommendations are empty or push notifications are not reported.
## Turn on logs
SDK logs appear in the Xcode console and are on by default. The SDK prints a line starting with `Error -` whenever it refuses to send an event, naming the missing field. Turn logs off with `SegmentifyManager.logStatus(isVisible: false)`.
## The event is not sent
The SDK checks required fields before sending. If one is missing it logs an error and **does not send the event**; no exception is thrown.
| Method | Not sent when |
| --- | --- |
| `sendPageView` | `category` is missing. |
| `sendProductView` | `productId`, `name`, `url`, `image` or `price` is missing; or both or neither of `category` and `categories` are set. |
| `sendAddOrRemoveBasket` | `step`, `productId` or `quantity` is missing. |
| `sendViewBasket`, `sendPurchase` and the other checkout methods | `totalPrice` or `productList` is missing. |
| `sendWishlist` | The step is unknown, or its `productId` or `favoritesList` is missing. |
| Push methods | The push data center URL is not set, or the token or `instanceId` is missing. |
## The event is sent but nothing happens
| Symptom | Likely cause |
| --- | --- |
| Nothing arrives in the panel | Wrong API key or data center URL, or the domain passed to the SDK is not the one registered for the account. |
| Events arrive, recommendations are empty | No active campaign for that page type, or the campaign is in test mode and the event is not (or the other way round). |
| No result for some users | `lang` or `currency` is missing or not configured for the account. |
| Product recommendations show wrong prices | `sendProductView` sends a different price or currency than your product feed. |
| Revenue is counted twice | `sendPurchase` is called more than once for an order. |
| Every launch looks like a new visitor | App data is cleared between launches, so the stored user ID is lost. |
## Push notifications
| Symptom | Likely cause |
| --- | --- |
| Users are not reachable | The token was never sent: check the registration call runs after the SDK is configured. |
| Sends are reported, views and clicks are not | `handlePushReceived` and `handlePushClicked` are not called, or the payload has no `instanceId`. |
| Nothing is reported at all | The push data center URL is not set or belongs to another region. |
## Check the request itself
The SDK calls the Segmentify Events API. To see exactly what a correct request and response look like, and to send one by hand, use the [API Docs](https://api-docs.segmentify.com/): the [status codes](https://api-docs.segmentify.com/events/responses-and-errors/) explain every rejection.
## Still stuck
Send the Segmentify support team the SDK version, the log lines around the event, and the time of the test.
---
# Copy for LLMs
> Give this documentation, or a Google Doc, to an LLM as clean Markdown
LLMs such as Claude or ChatGPT read Markdown far better than a copied web page or a Word-style document: headings, lists, tables and code blocks keep their structure, and no navigation, styling or long URLs waste the context window. This site, and the Google Docs we write alongside it, can both be handed to an LLM as Markdown.
## Copy a page of this site
- **Copy for LLMs**: the button under the title of every page copies the page as Markdown (title, description and content). Paste it into the LLM.
- **View as Markdown**: every page is also served as a Markdown file: replace the trailing slash of the page address with `.md`, so `…/some-page/` becomes `…/some-page.md`.
- **llms.txt**: [`llms.txt`](../llms.txt) lists every page of the site with a link to its Markdown file, following the [llms.txt](https://llmstxt.org/) convention. Give its address to an LLM or agent that can browse.
- **llms-full.txt**: [`llms-full.txt`](../llms-full.txt) is the whole site in one Markdown file, for a tool that should read all of it at once.
## Export a Google Doc as Markdown (Google Docs Copy for LLMs)
Specs, analyses and meeting notes often start in Google Docs. To give one to an LLM, or to move it into this documentation, export it as Markdown with the **Better Google Docs Copy** Chrome extension (its project is called "Google Docs Copy for LLMs"):
1. Install it from the [Chrome Web Store](https://chromewebstore.google.com/detail/better-google-docs-copy/faciokbjemdddkjokcajndenapikgcml).
2. Open the Google Doc and click **Copy for LLM**.
3. The first time, sign in with your Google account and allow access. The extension reads the document through the Google Docs API and its comments through the Google Drive API.
4. Choose whether to copy the selected text or the whole document, then paste the Markdown where you need it.
What it adds over a plain copy:
- **Comments**: comment threads come along with the passage they were left on, so the LLM sees the review discussion too.
- **Images**: Google's very long image URLs are replaced with short references, so they do not fill the context window.
- **Options** (right-click the extension icon, then Options): heading style (ATX `# Heading` or Setext), comment format (XML tags, blockquote or quoted context) and whether resolved comments are included.
The extension runs in the browser and only talks to Google's APIs. Before pasting a document into an external LLM, check that it holds no customer data, credentials or other information that must not leave the company.
### Without the extension
Google Docs can export Markdown itself, without comments:
- **Whole document**: File → Download → Markdown (.md).
- **A selection**: turn on Tools → Preferences → Enable Markdown, then use Edit → Copy as Markdown.
## Move a Google Doc into this documentation
1. Export the doc as Markdown as described above (leave comments out, or resolve them first).
2. Save it as a new `.md` file under `src/content/docs/`, with `title` and `description` front matter.
3. Add the page to the `sidebar` in `astro.config.mjs`, and open a pull request.