iOS SDK
The Monetai iOS SDK allows you to integrate our purchase prediction engine directly into your iOS app. This guide will walk you through the entire process, from installation to using key features like event tracking and purchaser prediction.
Prerequisitesβ
- iOS
13.0or higher - Xcode
12.0or higher
π Additional Resourcesβ
- GitHub Repository: https://github.com/hayanmind/monetai-ios
- Example Apps: Check out various integration examples in the
Examplesfolder of the GitHub repository- Swift Examples:
SimpleApp,SwiftPackageManagerExample,CocoaPodsExample - Objective-C Examples:
SimpleAppObjectiveC
- Swift Examples:
π§ Language Supportβ
The Monetai iOS SDK supports both Swift and Objective-C. Select the appropriate tab below based on your project's language.
Essential SDK Setupβ
π This section covers the essential steps to install the Monetai SDK and configure it to collect the data needed for purchase predictions.
Please make sure to follow all three steps to lay the foundation for all promotion features.
1. SDK Installationβ
Add the Monetai iOS SDK to your project using Swift Package Manager or CocoaPods.
- Swift Package Manager
- CocoaPods
- In Xcode, go to File > Add Package Dependencies
- Enter the repository URL:
https://github.com/hayanmind/monetai-ios - Select the latest version and click Add Package
- Choose your target and click Add Package
Add the following to your Podfile:
pod 'MonetaiSDK'
Then run:
pod install
2. SDK Initializationβ
Initialize the SDK when your app launches.
- Swift
- Objective-C
import MonetaiSDK
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize Monetai SDK
Task {
do {
let result = try await MonetaiSDK.shared.initialize(
sdkKey: "YOUR_SDK_KEY", // SDK key issued from Monetai dashboard
userId: "USER_ID", // User ID of your app's user
useStoreKit2: true // Set based on the purchase logic implemented in your app
)
print("Monetai SDK initialization completed:", result)
} catch {
print("Monetai SDK initialization failed:", error)
}
}
return true
}
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| sdkKey | string | SDK key issued from Monetai (Settings > SDK Integration) |
| userId | string | User ID of your app's user (if not available, use a unique identifier such as email or device ID) |
| useStoreKit2 | boolean? | Whether to use StoreKit2 (set based on the purchase logic implemented in your app, default: false) |
Return Value
| Return Value | Type | Description |
|---|---|---|
| organizationId | number | Organization ID |
| platform | 'ios' | Platform info |
| version | string | SDK version |
| userId | string | Set user ID |
| group | ABTestGroup | null | A/B test group |
#import <MonetaiSDK/MonetaiSDK.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize Monetai SDK
[[MonetaiSDK shared] initializeWithSdkKey:@"YOUR_SDK_KEY"
userId:@"USER_ID"
useStoreKit2:YES
completion:^(InitializeResult * _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"Monetai SDK initialization failed: %@", error);
} else {
NSLog(@"Monetai SDK initialization completed: %@", result);
}
}];
return YES;
}
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| sdkKey | string | SDK key issued from Monetai (Settings > SDK Integration) |
| userId | string | User ID of your app's user |
| useStoreKit2 | boolean? | Whether to use StoreKit2 (set based on the purchase logic implemented in your app, default: false) |
Return Value
| Return Value | Type | Description |
|---|---|---|
| organizationId | number | Organization ID |
| platform | 'ios' | Platform info |
| version | string | SDK version |
| userId | string | Set user ID |
| groupString | string | null | A/B test group (string) |
ABTestGroup Type
| Value | Description |
|---|---|
| monetai | Experimental group with automatic promotion |
| baseline | Control group without promotion |
| unknown | Users not included in campaign |
| null | When no current campaign exists |
3. Logging User Eventsβ
This is a critical step. Monetai's AI model relies entirely on the user events you log to analyze behavior and predict purchase intent. Without this data, the prediction feature will not function.
- Swift
- Objective-C
import MonetaiSDK
// Basic event logging
await MonetaiSDK.shared.logEvent(eventName: "app_in")
// Event logging with parameters
await MonetaiSDK.shared.logEvent(
eventName: "screen_in",
params: ["screen": "home"]
)
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| eventName | string | Event name |
| params | object? | Event parameters (optional) |
#import <MonetaiSDK/MonetaiSDK.h>
// Basic event logging
[[MonetaiSDK shared] logEventWithEventName:@"app_in" params:nil];
// Event logging with parameters
NSDictionary *params = @{
@"screen": @"home"
};
[[MonetaiSDK shared] logEventWithEventName:@"screen_in" params:params];
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| eventName | string | Event name |
| params | object? | Event parameters (optional) |
- Log all in-app events. Monetai will automatically select events most relevant to non-payer prediction for training.
- If no events are logged, instrument events on key features or buttons, especially those that occur before a purchase.
Events logged before the SDK is initialized are queued and sent automatically once initialization is complete.
Important: Even with the same event name, different parameters create different events that the AI model recognizes separately. Using too many diverse parameter values can reduce model accuracy.
Best Practices:
- β
Good:
["screen": "home"],["button": "upgrade"],["category": "premium"] - β Avoid:
["timestamp": "2024-01-15T10:30:00Z"],["userId": "user123"],["sessionId": "abc123"]
Why? Parameters like timestamps, user IDs, or session IDs create unique events for each occurrence, making it difficult for the model to find patterns. Focus on parameters that represent user behavior categories rather than specific instances.
Implementing Promotionsβ
π With the essential setup complete, this section dives into implementing the core promotion logic.
You'll learn how to trigger purchase predictions and use the results to display your custom promotional UI.
1. Predicting Purchasesβ
CCall the predict() function at a key purchase decision moment within your app to predict whether a user is likely to make a purchase.
- To optimize the user experience and most clearly measure campaign performance, we strongly recommend calling the
predict()function at only one specific point in the user journey. - It's most effective to call it at the critical moment of hesitationβafter the user has recognized the product's value but is still deciding whether to purchase.
Depending on your app's characteristics, consider points like:- When the user navigates away from the full-price subscription page.
- When the user completes a core workflow or task.
- When the user attempts to access or use a premium feature.
- Swift
- Objective-C
import MonetaiSDK
func predictUserPurchase() async {
do {
let result = try await MonetaiSDK.shared.predict()
print("Prediction result:", result.prediction)
print("Test group:", result.testGroup)
if result.prediction == .nonPurchaser {
// When predicted as non-purchaser, offer discount
print("Predicted as non-purchaser - discount can be applied")
} else if result.prediction == .purchaser {
// When predicted as purchaser
print("Predicted as purchaser - discount not needed")
}
} catch {
print("Prediction failed:", error)
}
}
API Reference
Return Value
| Return Value | Type | Description |
|---|---|---|
| prediction | PredictResult | Prediction result |
| testGroup | ABTestGroup | A/B test group |
PredictResult Type
| Value | Description |
|---|---|
| nonPurchaser | Predicted not to purchase |
| purchaser | Predicted to purchase |
| null | Cannot predict (before model creation or no active campaign) |
#import <MonetaiSDK/MonetaiSDK.h>
- (void)predictUserPurchase {
[[MonetaiSDK shared] predictWithCompletion:^(PredictResponse * _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"Prediction failed: %@", error);
return;
}
NSLog(@"Prediction result: %@", result.predictionString);
NSLog(@"Test group: %@", result.testGroupString);
if ([result.predictionString isEqualToString:@"non-purchaser"]) {
// When predicted as non-purchaser, offer discount
NSLog(@"Predicted as non-purchaser - discount can be applied");
} else if ([result.predictionString isEqualToString:@"purchaser"]) {
// When predicted as purchaser
NSLog(@"Predicted as purchaser - discount not needed");
}
}];
}
API Reference
Return Value
| Return Value | Type | Description |
|---|---|---|
| predictionString | string | null | Prediction result (string) |
| testGroupString | string | null | A/B test group (string) |
PredictResult String Values
| Value | Description |
|---|---|
| "non-purchaser" | Predicted not to purchase |
| "purchaser" | Predicted to purchase |
| null | Cannot predict (before model creation or no active campaign) |
predict() Function- Multiple Calls
- When a promotion is already active from a previous
predict()call, callingpredict()multiple times will not start a new promotion.
- When a promotion is already active from a previous
- Restarting Promotions
- After a promotion period ends, calling
predict()again will start a new promotion if the user is still predicted as a non-paying user.
- After a promotion period ends, calling
- Handling Existing Subscribers
- If you do not want to provide promotions to users who are already on paid subscriptions, do not call the
predict()function for those users.
- If you do not want to provide promotions to users who are already on paid subscriptions, do not call the
2. Displaying Promotion UIβ
When predict() identifies a user as a non-paying user, the SDK delivers discount information via the onDiscountInfoChange callback. You can use this to display promotional UI to the user.
A. Quick Start with UI Templates (Recommended)β
Pass paywallConfig to MonetaiSDK.shared.configurePaywall(). When predict() returns a non-purchaser and the discount is within its valid period, the banner/paywall will appear automatically.
Paywall UI templates are supported in iOS SDK 1.2.0 and above.
See available template styles and examples: UI Template Design Guide
- Swift
- Objective-C
import MonetaiSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Configure paywall
configurePaywall()
// Set subscription status (set initial value based on the user's actual subscription status)
MonetaiSDK.shared.setSubscriptionStatus(false)
}
private func configurePaywall() {
let features = [
Feature(title: "All premium features", description: "Unlock everything", isPremiumOnly: true),
Feature(title: "Advanced analytics", description: "Insights and detailed reports"),
Feature(title: "Priority support", description: "24/7 customer support")
]
let config = PaywallConfig(
discountPercent: 50,
regularPrice: "$10.00",
discountedPrice: "$5.00",
locale: "en",
style: .highlightBenefits,
features: features,
enabled: true,
bannerBottom: 20
)
config.onPurchase = { [weak self] close in
// TODO: Trigger your purchase flow
// On success, close paywall and update subscriber state
close()
MonetaiSDK.shared.setSubscriptionStatus(true)
}
config.onTermsOfService = {
// TODO: Open Terms of Service
}
config.onPrivacyPolicy = {
// TODO: Open Privacy Policy
}
MonetaiSDK.shared.configurePaywall(config)
}
}
#import <MonetaiSDK/MonetaiSDK.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Configure paywall
[self configurePaywall];
// Set subscription status (set initial value based on the user's actual subscription status)
[[MonetaiSDK shared] setSubscriptionStatus:NO];
}
- (void)configurePaywall {
// Create features
Feature *feature1 = [[Feature alloc] initWithTitle:@"All premium features"
description:@"Unlock everything"
isPremiumOnly:YES];
Feature *feature2 = [[Feature alloc] initWithTitle:@"Advanced analytics"
description:@"Insights and detailed reports"
isPremiumOnly:NO];
Feature *feature3 = [[Feature alloc] initWithTitle:@"Priority support"
description:@"24/7 customer support"
isPremiumOnly:NO];
NSArray<Feature *> *features = @[feature1, feature2, feature3];
// Create paywall config
PaywallConfigOptions *options = [[PaywallConfigOptions alloc] init];
options.features = features;
options.enabled = @YES;
options.bannerBottom = @20.0;
PaywallConfig *config = [[PaywallConfig alloc] initWithDiscountPercent:50
regularPrice:@"$10.00"
discountedPrice:@"$5.00"
locale:@"en"
style:PaywallStyleHighlightBenefits
options:options];
// Set callbacks
config.onPurchase = ^(void (^close)(void)) {
// TODO: Trigger your purchase flow
// On success, close paywall and update subscriber state
close();
[[MonetaiSDK shared] setSubscriptionStatus:YES];
};
config.onTermsOfService = ^{
// TODO: Open Terms of Service
};
config.onPrivacyPolicy = ^{
// TODO: Open Privacy Policy
};
[[MonetaiSDK shared] configurePaywall:config];
}
@end
PaywallConfig
- Swift
- Objective-C
| Key | Type | Required | Description |
|---|---|---|---|
| discountPercent | Int | β | Discount percentage (0-100) |
| regularPrice | String | β | Regular price label |
| discountedPrice | String | β | Discounted price label |
| locale | String | β | Language code (e.g., "en", "ko") |
| style | PaywallStyle | β | Template style |
| features | [Feature] | - | Only needed for .highlightBenefits or .keyFeatureSummary |
| enabled | Bool | - | Enable automatic banner/paywall display (default: true) |
| bannerBottom | CGFloat | - | Bottom offset for the floating banner (default: 20) |
| Key | Type | Required | Description |
|---|---|---|---|
| discountPercent | Int | β | Discount percentage (0-100) |
| regularPrice | String | β | Regular price label |
| discountedPrice | String | β | Discounted price label |
| locale | String | β | Language code (e.g., "en", "ko") |
| style | PaywallStyle | β | Template style |
| options | PaywallConfigOptions? | - | Options object for optional configuration |
PaywallConfigOptions
| Key | Type | Description |
|---|---|---|
| features | [Feature]? | Only needed for .highlightBenefits or .keyFeatureSummary |
| enabled | NSNumber? | Enable automatic banner/paywall display (default: true) |
| bannerBottom | NSNumber? | Bottom offset for the floating banner (default: 20) |
PaywallStyle Types
- Swift
- Objective-C
| Value | Description |
|---|---|
.compact | Compact design |
.highlightBenefits | Highlight benefits design |
.keyFeatureSummary | Key feature summary design |
.textFocused | Text-focused design |
| Value | Description |
|---|---|
PaywallStyleCompact | Compact design |
PaywallStyleHighlightBenefits | Highlight benefits design |
PaywallStyleKeyFeatureSummary | Key feature summary design |
PaywallStyleTextFocused | Text-focused design |
Feature Model
| Property | Type | Description |
|---|---|---|
| title | String | Feature title |
| description | String | Feature description |
| isPremiumOnly | Bool | Whether feature is premium only (default: false) |
Callbacks
| Callback | Type | Description |
|---|---|---|
| onPurchase | ((@escaping () -> Void) -> Void)? | Purchase button callback (call close() on success) |
| onTermsOfService | (() -> Void)? | Terms of Service click callback |
| onPrivacyPolicy | (() -> Void)? | Privacy Policy click callback |
Subscription Status Management
The SDK automatically controls banner/paywall visibility based on the user's subscription status. Use these methods to manage the subscription state:
- Swift
- Objective-C
// Set initial subscription status (can be called before or after configurePaywall)
MonetaiSDK.shared.setSubscriptionStatus(true) // true for subscribers, false for non-subscribers
// Set initial subscription status (can be called before or after configurePaywall)
[[MonetaiSDK shared] setSubscriptionStatus:YES]; // YES for subscribers, NO for non-subscribers
Automatic Banner Control
When paywall is configured, the SDK automatically:
- Shows the banner when discount is active, paywall is enabled, and user is not a subscriber
- Hides the banner when user is a subscriber, no discount exists, discount has expired, or paywall is disabled
B. Custom UI (Advanced)β
B-1. Implementation using onDiscountInfoChange callback
You can build your own promotion screen. The Monetai SDK provides the discount timing (startedAt and endedAt) and triggers the onDiscountInfoChange callback. Your app can use this information to implement the custom UI components.
The startedAt and endedAt values in the discount information indicate the valid period for the promotion. You should use these timestamps to:
- Show your promotion screen only during the valid period
- Hide the screen when the period expires
Important: The onDiscountInfoChange callback must be registered before calling initialize().
Registering the callback later may cause you to miss existing active promotion information. This can lead to issues where previously activated promotions cannot be displayed immediately when the app restarts.
The onDiscountInfoChange callback is triggered both when the app starts and there's valid discount information and when a new discount is generated by a predict() call. Use it to update banners, prices, or other UI elements in real-time.
- Swift
- Objective-C
import MonetaiSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set up discount info change callback
MonetaiSDK.shared.onDiscountInfoChange = { [weak self] discountInfo in
DispatchQueue.main.async {
self?.handleDiscountInfoChange(discountInfo)
}
}
}
private func handleDiscountInfoChange(_ discountInfo: AppUserDiscount?) {
if let discount = discountInfo {
// Update UI when discount info is available
let now = Date()
let endTime = discount.endedAt
if now < endTime {
// When discount is valid
showDiscountBanner(discount)
}
} else {
// When no discount info
hideDiscountBanner()
}
}
private func showDiscountBanner(_ discount: AppUserDiscount) {
// Show discount banner logic
print("Show discount banner:", discount)
}
private func hideDiscountBanner() {
// Hide discount banner logic
print("Hide discount banner")
}
}
API Reference
Callback Type
public var onDiscountInfoChange: ((AppUserDiscount?) -> Void)?
AppUserDiscount Type
| Property | Type | Description |
|---|---|---|
| startedAt | Date | Discount start time |
| endedAt | Date | Discount end time |
| appUserId | string | User ID |
| sdkKey | string | SDK key |
#import <MonetaiSDK/MonetaiSDK.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Set up discount info change callback
[MonetaiSDK shared].onDiscountInfoChangeCallback = ^(AppUserDiscount * _Nullable discountInfo) {
dispatch_async(dispatch_get_main_queue(), ^{
[self handleDiscountInfoChange:discountInfo];
});
};
}
- (void)handleDiscountInfoChange:(AppUserDiscount *)discountInfo {
if (discountInfo) {
// Update UI when discount info is available
NSDate *now = [NSDate date];
NSDate *endTime = discountInfo.endedAt;
if ([now compare:endTime] == NSOrderedAscending) {
// When discount is valid
[self showDiscountBanner:discountInfo];
}
} else {
// When no discount info
[self hideDiscountBanner];
}
}
- (void)showDiscountBanner:(AppUserDiscount *)discount {
// Show discount banner logic
NSLog(@"Show discount banner: %@", discount);
}
- (void)hideDiscountBanner {
// Hide discount banner logic
NSLog(@"Hide discount banner");
}
@end
API Reference
Callback Type
public var onDiscountInfoChangeCallback: ((Any?) -> Void)?
AppUserDiscount Type
| Property | Type | Description |
|---|---|---|
| startedAt | Date | Discount start time |
| endedAt | Date | Discount end time |
| appUserId | string | User ID |
| sdkKey | string | SDK key |
B-2. Reactive implementation using currentDiscount property
You can use the currentDiscount property to immediately access currently active discount information. You can check the current discount status without the onDiscountInfoChange callback.
The onDiscountInfoChange callback has a constraint that it must be registered before calling initialize() to avoid missing events. However, if you want to bypass this constraint and implement in a more flexible way, you can consider using reactive processing with @Published objects and Combine.
API Reference
Current discount information property
@Published public private(set) var currentDiscount: AppUserDiscount?
Managing User Stateβ
SDK Resetβ
Initialize the SDK when the user logs out.
- Swift
- Objective-C
import MonetaiSDK
// When user logs out
func logoutUser() {
MonetaiSDK.shared.reset()
print("User logout completed")
}
#import <MonetaiSDK/MonetaiSDK.h>
// When user logs out
- (void)logoutUser {
[[MonetaiSDK shared] reset];
NSLog(@"User logout completed");
}
Support
If you run into any trouble during the integration, don't hesitate to contact us at support@monetai.io.
Next Stepsβ
With the SDK setup complete, you're ready to create a model and launch a campaign: