> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gameball.co/llms.txt
> Use this file to discover all available pages before exploring further.

# How Do I Track Referrals with the iOS SDK (v4)?

> Implement referral tracking using mobile deep linking providers (Branch or Adjust)

# Implement Mobile Referrals

Gameball referrals for mobile apps rely on **deep links** generated by a provider such as **Branch** or **Adjust**.\
The deep link provider attaches a referral code to the link, and your app extracts it and passes it to Gameball when registering the new customer.

> Firebase Dynamic Links are no longer supported for new integrations.\
> Use **Branch** or **Adjust** instead.

***

## Setup Overview

**1. Choose a Deep Link Provider**

Use **Branch** or **Adjust** to generate referral links and handle deep/deferred linking in your iOS app.

**2. Install the Provider SDK**

Add the provider SDK (Branch or Adjust) via Swift Package Manager following their official documentation.

**3. Configure Deep Linking**

Configure Universal Links / URL schemes and deferred deep linking according to your provider's guide.

**4. Connect Provider in Gameball**

In the Gameball dashboard, go to

**Settings → Admin Settings → Integration → Mobile Configuration → Dynamic Link Provider**

and connect your Branch or Adjust configuration.

> [!NOTE]
>
> Gameball will instruct your deep link provider to append a referral identifier\
> (e.g. `?referrerCode=SARAH123`) to each referral link.

***

## Handling Deep Links on iOS

Your deep link provider (Branch / Adjust) will call a callback with link parameters whenever:

* The app is opened from a referral link (cold start), or
* The app is already running and receives a deep link (warm start).

You only need to:

1. Extract the **referrer code** from the provider’s payload
2. Temporarily store it (e.g. in `UserDefaults`)
3. Use it when you call `InitializeCustomerRequest`

### Example: Extract & Store Referrer Code

This example assumes you already integrated Branch/Adjust and are receiving a `params` or `userInfo` dictionary from their SDK.

```swift theme={null}
func handleDeepLinkParameters(_ params: [String: Any]) {
    // Gameball-configured key for referral code (example: "referrerCode")
    if let referrerCode = params["referrerCode"] as? String {
        // Persist until registration
        UserDefaults.standard.set(referrerCode, forKey: "pendingReferralCode")
        print("Stored referrer code: \(referrerCode)")
    }
}
```

> [!NOTE]
>
> Follow the official [Branch](https://gameball.mintlify.app/tutorials/experiences/more/branch-io-integration) / [Adjust](https://gameball.mintlify.app/tutorials/experiences/more/adjust-integration) integration guides for the exact initialization and callback code.
>
> Your only Gameball-specific responsibility is extracting`referrerCode` and saving it.

***

## SwiftUI Integration (Conceptual Flow)

In SwiftUI, you can still use an AppDelegate adaptor or handle incoming URLs via .onOpenURL, and then forward the resolved parameters to handleDeepLinkParameters.

```swift theme={null}
import SwiftUI

@main
struct YourApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

> [!NOTE]
>
> And inside your Branch / Adjust callback (which might still live in AppDelegate or another handler), forward the parameters:

```swift theme={null}
func didReceiveDeepLinkParameters(_ params: [String: Any]) {
    handleDeepLinkParameters(params)
}
```

***

## Register Customer with Referral Code

When the new customer completes registration or first login, include the stored referrer code (if any) in `InitializeCustomerRequest`.

```swift theme={null}
import Gameball

func registerNewCustomer(customerId: String, email: String) {
    let savedReferrerCode = UserDefaults.standard.string(forKey: "pendingReferralCode")

    do {
        let customerRequest = try InitializeCustomerRequest(
            customerId: customerId,
            email: email,
            referralCode: savedReferrerCode // Pass to Gameball if available
        )

        GameballApp.getInstance().initializeCustomer(customerRequest) { _, errorMessage in
            if let errorMessage = errorMessage {
                print("Referral registration error: \(errorMessage)")
            } else {
                UserDefaults.standard.removeObject(forKey: "pendingReferralCode")
            }
        }
    } catch {
        print("Validation error: \(error.localizedDescription)")
    }
}
```

> [!TIP]
>
> Always clear the stored referral code after the customer successfully registers, to avoid it being applied again later.

***

## Get Customer Referral Link

Use the SDK to retrieve a customer’s unique referral code and shareable link.

```swift theme={null}
GameballApp.getInstance().getCustomerReferralInfo(for: "customer-123") { result in
    switch result {
    case .success(let referralInfo):
        let referralCode = referralInfo.referralCode
        let referralLink = referralInfo.referralLink

        // Use in your UI or share flow
        print("Referral code: \(referralCode)")
        showShareSheet(with: referralLink)
    case .failure(let error):
        print("Failed to load referral info: \(error.localizedDescription)")
    }
}
```

***

## Share Referral Link

### UIKit

```swift theme={null}
func shareReferralLink(_ referralLink: String, from viewController: UIViewController) {
    let message = "Join me on our app! Use my referral link: \(referralLink)"
    let activityVC = UIActivityViewController(
        activityItems: [message],
        applicationActivities: nil
    )

    viewController.present(activityVC, animated: true)
}
```

***

### SwiftUI

```swift theme={null}
import SwiftUI
import Gameball

struct ReferralShareView: View {
    @State private var showShareSheet = false
    @State private var referralLink = ""

    var body: some View {
        Button("Share Referral Link") {
            fetchReferralLink()
        }
        .sheet(isPresented: $showShareSheet) {
            ActivityView(activityItems: ["Join me on our app! Use my referral link: \(referralLink)"])
        }
    }

    func fetchReferralLink() {
        GameballApp.getInstance().getCustomerReferralInfo(for: "customer-123") { result in
            if case .success(let info) = result {
                referralLink = info.referralLink
                showShareSheet = true
            }
        }
    }
}

struct ActivityView: UIViewControllerRepresentable {
    let activityItems: [Any]

    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    }

    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}
```

***

## Referral Flow Summary

**1. Referrer Gets a Link**

Existing customer retrieves their unique referral link from the app (via `getCustomerReferralInfo`).

**2. Referrer Shares Link**

The link is shared through social networks, messaging apps, or email.

**3. New User Opens Link**

The new customer installs or opens the app via a deep link (Branch/Adjust).

**4. App Captures Referrer Code**

Your deep link provider passes parameters, and you store the `referrerCode` temporarily.

**5. New User Registers**

When the new customer registers, you call `initializeCustomer` with the stored `referralCode`.

**6. Rewards Are Granted**

Gameball rewards the referrer and the referred customer based on your referral program configuration.

> [!NOTE]
>
> Configure referral rules, rewards, and eligibility in your Gameball dashboard.
>
> The SDK’s job is to pass the correct `referralCode` at registration and provide the sharable referral link.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.