The official iOS SDK for Insert Affiliate - track affiliate-driven in-app purchases and reward your partners automatically.
What does this SDK do? It connects your iOS app to Insert Affiliate's platform, enabling you to track which affiliates drive subscriptions and automatically pay them commissions when users make in-app purchases.
- Quick Start (5 Minutes)
- Essential Setup
- Verify Your Integration
- Advanced Features
- Troubleshooting
- Support
Get up and running with minimal code to validate the SDK works before tackling IAP and deep linking setup.
- iOS 13.0+ and Swift 5.0+
- Xcode 12.0+
- Company Code from your Insert Affiliate dashboard
Step 1: Open your Xcode project
Step 2: Go to File > Add Packages
Step 3: Enter the repository URL:
https://github.com/Insert-Affiliate/InsertAffiliateSwiftSDK.git
Step 4: Select the branch main and confirm
Alternative: Swift Package Manager
Add to your Package.swift:
.package(url: "https://github.com/Insert-Affiliate/InsertAffiliateSwiftSDK.git", branch: "main")Add this minimal code to your AppDelegate.swift to test the SDK:
import InsertAffiliateSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Initialize SDK with verbose logging (recommended during setup)
InsertAffiliateSwift.initialize(
companyCode: "YOUR_COMPANY_CODE", // Get from https://app.insertaffiliate.com/settings
verboseLogging: true // Enable verbose logging for setup
)
return true
}
}For SwiftUI apps:
import SwiftUI
import InsertAffiliateSwift
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE", verboseLogging: true)
return true
}
}Expected Console Output:
When the SDK initializes successfully, you'll see logs confirming initialization:
[InsertAffiliateSwift] SDK initialized with company code: YOUR_COMPANY_CODE
[InsertAffiliateSwift] Verbose logging enabled
β If you see these logs, the SDK is working! Now proceed to Essential Setup below.
verboseLogging: false or omitting it.
Complete these three required steps to start tracking affiliate-driven purchases.
The SDK must be initialized in your AppDelegate before using any features. You've already done the basic initialization above, but here are additional options:
// Minimal setup with verbose logging enabled (recommended during development)
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE", verboseLogging: true)Advanced Initialization Options (click to expand)
// With Insert Links enabled (for Insert Affiliate's built-in deep linking)
InsertAffiliateSwift.initialize(
companyCode: "YOUR_COMPANY_CODE",
verboseLogging: true, // Enable verbose logging
insertLinksEnabled: true, // Enable Insert Links
insertLinksClipboardEnabled: true, // Enable clipboard access (triggers permission prompt)
affiliateAttributionActiveTime: 604800, // Optional: 7 days attribution timeout (default: no timeout)
preventAffiliateTransfer: true // Optional: Protect original affiliate from being overwritten
)Parameters:
verboseLogging: Shows detailed logs for debugging (disable in production)insertLinksEnabled: Set totrueif using Insert Links,falseif using Branch/AppsFlyerinsertLinksClipboardEnabled: Enables clipboard-based attribution for Insert Links. When enabled:- How it works: When a user clicks an Insert Link, the affiliate identifier is automatically copied to their clipboard
- What the SDK does: On app launch, the SDK checks the clipboard for Insert Affiliate identifiers and applies them
- Why it's useful: This massively increases attribution success rate and accuracy by providing a reliable fallback when direct deep linking fails (e.g., user manually opens app later, deep link doesn't work, app wasn't installed yet, etc.)
- User experience: iOS will show a one-time permission prompt: "[Your App] would like to paste from [App Name]"
- Recommendation: Strongly recommended for maximum attribution accuracy, though users will see the clipboard permission prompt
affiliateAttributionActiveTime: How long affiliate attribution lasts in seconds (0 = never expires)preventAffiliateTransfer: Whentrue, protects the original affiliate from being overwritten by subsequent affiliate links. Learn more
Insert Affiliate requires a receipt verification method to validate purchases. Choose ONE of the following:
| Method | Best For | Setup Time | Complexity |
|---|---|---|---|
| RevenueCat | Most developers, managed infrastructure | ~10 min | β Simple |
| Adapty | Paywall A/B testing, analytics | ~10 min | β Simple |
| Iaptic | Custom requirements, direct control | ~15 min | ββ Medium |
| App Store Direct | No 3rd party fees (subscriptions only) | ~20 min | ββ Medium |
| Apphud | Alternative managed infrastructure | ~10 min | β Simple |
Step 1: Code Setup
Complete the RevenueCat SDK installation first, then modify your AppDelegate.swift:
import SwiftUI
import RevenueCat
import InsertAffiliateSwift
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
Purchases.configure(withAPIKey: "YOUR_REVENUE_CAT_API_KEY")
// Set up callback to sync affiliate attributes to RevenueCat whenever they change
// Note: Use preventAffiliateTransfer in initialize() to block affiliate changes in the SDK
InsertAffiliateSwift.setInsertAffiliateIdentifierChangeCallback { identifier, offerCode in
guard let identifier = identifier else { return }
// Ensure subscriber exists before setting attributes
Purchases.shared.getCustomerInfo { customerInfo, error in
guard let customerInfo = customerInfo else { return }
// OPTIONAL: Prevent attribution for existing subscribers
// Uncomment to ensure affiliates only earn from users they actually brought:
// if !customerInfo.entitlements.active.isEmpty { return } // User already subscribed, don't attribute
// Set attributes for tracking and targeting
var attributes: [String: String] = [
"insert_affiliate": identifier,
"insert_timedout": "" // Clear timeout flag
]
if let offerCode = offerCode {
attributes["affiliateOfferCode"] = offerCode // For RevenueCat targeting
}
Purchases.shared.attribution.setAttributes(attributes)
// Sync to enable targeting based on affiliateOfferCode
Purchases.shared.syncAttributesAndOfferingsIfNeeded { offerings, error in
print("Offerings synced, current: \(offerings?.current?.identifier ?? "none")")
}
}
}
// Initialize Insert Affiliate SDK
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE", verboseLogging: true)
// Sync existing affiliate on app launch
if let existingAffiliate = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
Purchases.shared.attribution.setAttributes(["insert_affiliate": existingAffiliate])
}
return true
}
}Replace YOUR_REVENUE_CAT_API_KEY with your RevenueCat API Key from here.
RevenueCat Targeting (Optional)
To show different offerings based on affiliate offer codes:
- In RevenueCat Dashboard, go to Project Settings β Targeting
- Create a rule: "When
affiliateOfferCodeequalsyourOfferCode, show offeringyour_special_offering" - The SDK automatically sets
affiliateOfferCodewhen an affiliate has one configured
Step 2: Webhook Setup
- In RevenueCat, create a new webhook
- Configure webhook settings:
- Webhook URL:
https://api.insertaffiliate.com/v1/api/revenuecat-webhook - Event Type: "All events"
- Webhook URL:
- In your Insert Affiliate dashboard:
- Set In-App Purchase Verification to
RevenueCat - Copy the
RevenueCat Webhook Authentication Headervalue
- Set In-App Purchase Verification to
- Back in RevenueCat webhook config:
- Paste the authentication header value into the Authorization header field
β RevenueCat setup complete! Now skip to Step 3: Set Up Deep Linking
Step 1: Code Setup
Complete the Adapty SDK installation first, then modify your AppDelegate.swift:
import SwiftUI
import Adapty
import InsertAffiliateSwift
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// Initialize Adapty
Adapty.activate("YOUR_ADAPTY_PUBLIC_SDK_KEY")
// Initialize Insert Affiliate
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE", verboseLogging: true)
// Set Insert Affiliate identifier as Adapty custom attribute
if let applicationUsername = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
Task {
do {
var builder = AdaptyProfileParameters.Builder()
builder = try builder.with(customAttribute: applicationUsername, forKey: "insert_affiliate")
try await Adapty.updateProfile(params: builder.build())
} catch {
print("Failed to set Adapty attribution: \(error.localizedDescription)")
}
}
}
return true
}
}Replace:
YOUR_ADAPTY_PUBLIC_SDK_KEYwith your Adapty Public SDK Key from Adapty DashboardYOUR_COMPANY_CODEwith your company code from Insert Affiliate Settings
Step 2: Handle Deep Link Attribution Updates
When using deep linking (Branch, AppsFlyer, or Insert Links), update Adapty when an affiliate identifier is set:
// Example with Branch.io
Branch.getInstance().initSession(launchOptions: launchOptions) { (params, error) in
if let referringLink = params?["~referring_link"] as? String {
InsertAffiliateSwift.setInsertAffiliateIdentifier(referringLink: referringLink) { result in
guard let shortCode = result else { return }
// Update Adapty with the new affiliate identifier
Task {
do {
var builder = AdaptyProfileParameters.Builder()
builder = try builder.with(customAttribute: shortCode, forKey: "insert_affiliate")
try await Adapty.updateProfile(params: builder.build())
print("[Adapty] Set insert_affiliate attribute: \(shortCode)")
} catch {
print("Failed to set Adapty attribution: \(error.localizedDescription)")
}
}
}
}
}Step 3: Webhook Setup
- In your Insert Affiliate dashboard:
- Set In-App Purchase Verification to
Adapty - Copy the
Adapty Webhook URL(for both production and sandbox) - Copy the
Adapty Webhook Authorization Headervalue
- Set In-App Purchase Verification to
- In the Adapty Dashboard:
- Navigate to Integrations β Webhooks
- Set Production URL and Sandbox URL to the webhook URL from Insert Affiliate
- Paste the authorization header value into Authorization header value
- Enable: Exclude historical events, Send attribution, Send trial price, Send user attributes
π View complete Adapty integration guide with examples β
β Adapty setup complete! Now skip to Step 3: Set Up Deep Linking
Step 1: Code Setup
Complete the Iaptic account setup and SDK installation. Then modify your AppDelegate.swift:
import SwiftUI
import InAppPurchaseLib
import InsertAffiliateSwift
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE")
// Define products
let iapProductsArray = [
IAPProduct(
productIdentifier: "YOUR_APPLE_IAP_SUBSCRIPTION_ID",
productType: .autoRenewableSubscription
)
]
// Reinitialise In-App Purchases
InAppPurchase.stop()
if let applicationUsername = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
InAppPurchase.initialize(
iapProducts: iapProductsArray,
validatorUrlString: "https://validator.iaptic.com/v3/validate?appName=YOUR_IAPTIC_APP_NAME&apiKey=YOUR_IAPTIC_PUBLIC_KEY",
applicationUsername: applicationUsername
)
} else {
InAppPurchase.initialize(
iapProducts: iapProductsArray,
validatorUrlString: "https://validator.iaptic.com/v3/validate?appName=YOUR_IAPTIC_APP_NAME&apiKey=YOUR_IAPTIC_PUBLIC_KEY"
)
}
return true
}
}Replace:
YOUR_IAPTIC_APP_NAMEwith your Iaptic App NameYOUR_IAPTIC_PUBLIC_KEYwith your Iaptic Public Key
Step 2: Webhook Setup
- Open the Insert Affiliate settings:
- Set the In-App Purchase Verification method to
Iaptic - Copy the
Iaptic Webhook URLandIaptic Webhook Sandbox URL
- Set the In-App Purchase Verification method to
- Go to Iaptic Settings:
- Paste the Webhook URLs into the corresponding fields
- Click Save Settings
- Complete the Iaptic App Store Server Notifications setup
β Iaptic setup complete! Now proceed to Step 3: Set Up Deep Linking
Step 1: Apple App Store Notification Setup
Visit our docs and complete the required App Store Server to Server Notifications setup.
Step 2: Implementing Purchases
// Within the function where you are making the purchase...
func purchase(productIdentifier: String) async {
do {
// Replace your product.purchase() with the lines below
let token = await InsertAffiliateSwift.returnUserAccountTokenAndStoreExpectedTransaction()
// Optional override: Use your own UUID for the purchase token
// let token = await InsertAffiliateSwift.returnUserAccountTokenAndStoreExpectedTransaction(
// overrideUUIDString: "YOUR_OWN_UUID"
// )
let result = try await product.purchase(options: token.map { [.appAccountToken($0)] } ?? [])
}
}β App Store Direct setup complete! Now proceed to Step 3: Set Up Deep Linking
Step 1: Code Setup
Complete the Apphud Quickstart and Setup. Then modify your AppDelegate.swift:
import SwiftUI
import ApphudSDK
import InsertAffiliateSwift
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
Apphud.start(apiKey: "YOUR_APPHUD_KEY")
if let applicationUsername = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
Apphud.setUserProperty(key: .init("insert_affiliate"), value: applicationUsername, setOnce: false)
}
return true
}
}Replace YOUR_APPHUD_KEY with your Apphud API Key.
Step 2: Webhook Setup
- Open the Insert Affiliate settings:
- Set the In-App Purchase Verification method to
Apphud - Copy the
Apphud Webhook URL
- Set the In-App Purchase Verification method to
- Go to the Apphud Dashboard:
- Navigate to Settings β iOS App Settings
- Paste the webhook URL into the
Proxy App Store server notifications to this URLfield - Click Save
β Apphud setup complete! Now proceed to Step 3: Set Up Deep Linking
Deep linking lets affiliates share unique links that track users to your app. Choose ONE deep linking provider:
| Provider | Best For | Complexity | Setup Guide |
|---|---|---|---|
| Insert Links | Simple setup, no 3rd party | β Simple | View |
| Branch.io | Robust attribution, deferred deep linking | ββ Medium | View |
| AppsFlyer | Enterprise analytics, comprehensive attribution | ββ Medium | View |
Insert Links is Insert Affiliate's built-in deep linking solutionβno third-party SDK required.
Prerequisites:
- Complete the Insert Links setup in the Insert Affiliate dashboard
Code Implementation:
import UIKit
import InsertAffiliateSwift
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// Initialize SDK with Insert Links enabled
InsertAffiliateSwift.initialize(
companyCode: "YOUR_COMPANY_CODE",
verboseLogging: true, // Enable for debugging
insertLinksEnabled: true, // Enable Insert Links
insertLinksClipboardEnabled: false // Set to true if attribution accuracy is most important (triggers clipboard permission prompt)
)
// Set up callback for affiliate identifier changes (receives identifier and optional offer code)
InsertAffiliateSwift.setInsertAffiliateIdentifierChangeCallback { identifier, offerCode in
if let identifier = identifier {
print("Affiliate identifier: \(identifier)")
if let offerCode = offerCode {
print("Offer code: \(offerCode)")
}
// If using RevenueCat, update attributes here
// Purchases.shared.attribution.setAttributes(["insert_affiliate": identifier])
// Purchases.shared.syncAttributesAndOfferingsIfNeeded { offerings, error in }
// If using Adapty, update attributes here
// Task {
// var builder = AdaptyProfileParameters.Builder()
// builder = try builder.with(customAttribute: identifier, forKey: "insert_affiliate")
// try await Adapty.updateProfile(params: builder.build())
// }
// If using Apphud, update property here
// Apphud.setUserProperty(key: .init("insert_affiliate"), value: identifier, setOnce: false)
}
}
// Handle deep link from app launch
if let url = launchOptions?[.url] as? URL {
InsertAffiliateSwift.handleInsertLinks(url)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
InsertAffiliateSwift.handleInsertLinks(url)
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
if let url = userActivity.webpageURL {
InsertAffiliateSwift.handleInsertLinks(url)
}
return true
}
}SwiftUI - On Open URL:
import InsertAffiliateSwift
import SwiftUI
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL(perform: { url in
// Handle InsertAffiliate deep links
if InsertAffiliateSwift.handleInsertLinks(url) {
if let affiliateIdentifier = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
// If using RevenueCat:
// Purchases.shared.attribution.setAttributes(["insert_affiliate": affiliateIdentifier])
// Purchases.shared.syncAttributesAndOfferingsIfNeeded { offerings, error in }
// If using Adapty:
// Task {
// var builder = AdaptyProfileParameters.Builder()
// builder = try builder.with(customAttribute: affiliateIdentifier, forKey: "insert_affiliate")
// try await Adapty.updateProfile(params: builder.build())
// }
// If using Apphud:
// Apphud.setUserProperty(key: .init("insert_affiliate"), value: affiliateIdentifier, setOnce: false)
}
}
})
}
}
}Testing Deep Links:
# Test with your iOS URL scheme from Insert Affiliate dashboard
xcrun simctl openurl booted "YOUR_IOS_URL_SCHEME://TEST_SHORT_CODE"β Insert Links setup complete! Skip to Verify Your Integration
Universal Links provide a better user experience than custom URL schemes. When a user taps an Insert Link and already has your app installed, iOS opens the app directly β without loading the browser and without showing a "Safari cannot open the page" error. If the app is not installed, the link opens normally in Safari with no error.
Prerequisites:
- Complete the Universal Links setup steps in the Insert Affiliate documentation β this includes entering your Apple Team ID and iOS Bundle Identifier in the dashboard settings
Step 1: Add Associated Domains in Xcode
Go to your app target β Signing & Capabilities β + Capability β Associated Domains.
Add the following:
applinks:insertaffiliate.link
If you have a custom domain set up (e.g. links.yourcompany.com), also add:
applinks:links.yourcompany.com
Step 2: Handle Universal Links in your app
The handleInsertLinks method accepts both custom URL scheme URLs and Universal Link URLs.
UIKit (AppDelegate)
Make sure your AppDelegate includes the continue userActivity method:
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
if let url = userActivity.webpageURL {
InsertAffiliateSwift.handleInsertLinks(url)
}
return true
}SwiftUI
In SwiftUI apps, Universal Links are delivered via the scene lifecycle, not the AppDelegate. .onOpenURL only handles custom URL schemes β you must also add .onContinueUserActivity for Universal Links:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
// Handles custom URL scheme (ia-companycode://)
InsertAffiliateSwift.handleInsertLinks(url)
}
.onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { userActivity in
// Handles Universal Links (https://insertaffiliate.link/...)
if let url = userActivity.webpageURL {
InsertAffiliateSwift.handleInsertLinks(url)
}
}
}
}
}Note: If you only add
.onOpenURL, Universal Links will open the app buthandleInsertLinkswill never be called and attribution will not be tracked.
Testing Universal Links:
# Test with your Insert Link URL
xcrun simctl openurl booted "https://insertaffiliate.link/YOUR_COMPANY_CODE/TEST_SHORT_CODE"
# Or with your custom domain
xcrun simctl openurl booted "https://links.yourcompany.com/YOUR_COMPANY_CODE/TEST_SHORT_CODE"Branch.io provides robust attribution and deferred deep linking capabilities.
Key Integration Steps:
- Install and configure Branch SDK for iOS
- Extract
~referring_linkfrom Branch callback - Pass to Insert Affiliate SDK using
setInsertAffiliateIdentifier()
π View complete Branch.io integration guide β
Includes full examples for:
- RevenueCat integration
- Adapty integration
- Apphud integration
- Iaptic integration
- App Store Direct integration
β After completing Branch setup, skip to Verify Your Integration
AppsFlyer provides enterprise-grade analytics and comprehensive attribution.
Key Integration Steps:
- Install and configure AppsFlyer SDK for iOS
- Create AppsFlyer OneLink in dashboard
- Extract deep link from
onAppOpenAttribution()callback - Pass to Insert Affiliate SDK using
setInsertAffiliateIdentifier()
π View complete AppsFlyer integration guide β
Includes full examples for:
- RevenueCat integration
- Adapty integration
- Iaptic integration
- App Store Direct integration
- Deferred deep linking setup
β After completing AppsFlyer setup, proceed to Verify Your Integration
Before going live, verify everything works correctly:
- SDK Initializes: Check console for
SDK initialized with company codelog - Affiliate Identifier Stored: Click a test affiliate link and verify identifier is stored
- Purchase Tracked: Make a test purchase and verify transaction is sent to Insert Affiliate
Test Deep Link (via Simulator):
# Replace with your actual deep link URL
xcrun simctl openurl booted "https://your-app.onelink.me/abc123"Check Stored Affiliate Identifier:
if let affiliateId = InsertAffiliateSwift.returnInsertAffiliateIdentifier() {
print("Current affiliate ID: \(affiliateId)")
}Expected Output: Current affiliate ID: AFFILIATE1-a1b2c3
| Issue | Solution |
|---|---|
| "Company code is not set" | Ensure initialize() is called in AppDelegate before any other SDK methods |
| "No affiliate identifier found" | User must click an affiliate link before making a purchase |
| Deep link opens browser instead of app | Verify associated domains in Xcode project and deep linking provider dashboard |
| Purchase not tracked | Check webhook configuration in IAP verification platform |
Track custom events beyond purchases (e.g., signups, referrals) to incentivize affiliates for specific actions.
// Track custom event (affiliate identifier must be set first)
InsertAffiliateSwift.trackEvent(eventName: "user_signup")Use Cases:
- Pay affiliates for signups instead of purchases
- Track trial starts, content unlocks, or other conversions
Short codes are unique, 3-25 character alphanumeric identifiers that affiliates can share (e.g., "SAVE20" in a TikTok video description).
Validate and Store Short Code:
Task {
let isValid = await InsertAffiliateSwift.setShortCode(shortCode: "SAVE20")
if isValid {
print("Short code is valid!")
// Show success message to user
} else {
print("Invalid short code")
// Show error message
}
}Get Affiliate Details Without Setting:
if let details = await InsertAffiliateSwift.getAffiliateDetails(affiliateCode: "SAVE20") {
print("Affiliate Name: \(details.affiliateName)")
print("Short Code: \(details.affiliateShortCode)")
print("Deep Link: \(details.deeplinkUrl)")
}Learn more: Short Codes Documentation
Automatically apply discounts or trials when users come from specific affiliates.
How It Works:
- Configure an offer code modifier in your Insert Affiliate dashboard (e.g.,
_oneWeekFree) - SDK automatically fetches and stores the modifier when affiliate identifier is set
- Use the modifier to construct dynamic product IDs
Quick Example:
var dynamicProductIdentifier: String {
let baseProductId = "oneMonthSubscription"
if let offerCode = InsertAffiliateSwift.OfferCode {
let cleanOfferCode = offerCode.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
return "\(baseProductId)\(cleanOfferCode)"
}
return baseProductId
}π View complete Dynamic Offer Codes guide β
Includes full examples for:
- App Store Connect setup
- RevenueCat integration with dynamic product selection
- Native StoreKit 2 integration
- Testing and troubleshooting
Control how long affiliate attribution remains active after a user clicks a link (e.g., 7-day attribution window).
Set Timeout During Initialization:
// 7-day attribution window (604800 seconds)
InsertAffiliateSwift.initialize(
companyCode: "YOUR_COMPANY_CODE",
affiliateAttributionActiveTime: 604800
)Check Attribution Validity:
let isValid = await InsertAffiliateSwift.isAffiliateAttributionValid()
if isValid {
// Attribution is still active
} else {
// Attribution expired
}Common Timeout Values:
- 1 day:
86400 - 7 days:
604800(recommended) - 30 days:
2592000 - No timeout: omit parameter (default)
Get Attribution Date:
if let storedDate = InsertAffiliateSwift.getAffiliateStoredDate() {
print("Affiliate stored on: \(storedDate)")
}Get Expiry Timestamp:
if let expiryTimestamp = InsertAffiliateSwift.getAffiliateExpiryTimestamp() {
print("Attribution expires at: \(expiryTimestamp) ms since epoch")
// Convert to Date if needed
let expiryDate = Date(timeIntervalSince1970: Double(expiryTimestamp) / 1000)
print("Expiry date: \(expiryDate)")
}Protect the original affiliate's attribution from being overwritten when users click different affiliate links.
Enable During Initialization:
InsertAffiliateSwift.initialize(
companyCode: "YOUR_COMPANY_CODE",
preventAffiliateTransfer: true
)How It Works:
- User clicks Affiliate A's link β Attribution stored
preventAffiliateTransfer: trueis set- User clicks Affiliate B's link β SDK detects existing attribution
- Transfer blocked β Affiliate B's link is silently ignored
- User purchases β Affiliate A receives commission
Use Cases:
- Prevent "affiliate stealing" scenarios
- Ensure the first affiliate to acquire a user always receives credit
- Protect long-term affiliate relationships
Learn more: Prevent Affiliate Transfer Documentation
Error: "Company code is not set"
- Cause: SDK not initialized or
initialize()called after other SDK methods - Solution: Call
InsertAffiliateSwift.initialize()inAppDelegate.application(_:didFinishLaunchingWithOptions:)before any other SDK methods
Problem: Deep link opens browser instead of app
- Cause: Missing or incorrect associated domains, or URL scheme not configured
- Solution:
- Verify associated domains in Xcode project match your deep linking provider's domain
- Add URL scheme to Info.plist
- For universal links, ensure apple-app-site-association file is properly configured
Problem: "No affiliate identifier found"
- Cause: User hasn't clicked an affiliate link yet
- Solution: Ensure users come from affiliate links before purchases. Test with simulator:
xcrun simctl openurl booted "YOUR_DEEP_LINK_URL"
Problem: Purchases not appearing in Insert Affiliate dashboard
- Cause: Webhook not configured or affiliate identifier not passed to IAP platform
- Solution:
- Verify webhook URL and authorization headers are correct
- For RevenueCat: Confirm
insert_affiliateattribute is set before purchase - For Iaptic/App Store Direct: Check that affiliate identifier exists when purchase is made
- Enable verbose logging and check console for errors
Enable detailed logs during development to diagnose issues:
InsertAffiliateSwift.initialize(companyCode: "YOUR_COMPANY_CODE", verboseLogging: true)Important: Disable verbose logging in production builds.
- π Documentation
- π¬ Dashboard Support
- π Report Issues
- Documentation: docs.insertaffiliate.com
- Dashboard Support: app.insertaffiliate.com/help
- Issues: GitHub Issues
- Company Code: Get yours from Settings
Need help getting started? Check out our quickstart guide or contact support.