---
title: iOS Integration
slug: pubtech-cmp/ios-integration
docTags: 
createdAt: 2024-05-27T07:55:48.436Z
---

The PubConsent SDK is the integration of our PubConsent CMP into iOS applications.

This integration doesn't require many updates since every change made inside the configurator will be reflected automatically.****
**We support iOS versions from 9 up to the latest one.**

:::hint{type="success"}
Whenever there are breaking changes, you'll be contacted via email to your technical email configured in our dashboard to enable you to update the SDK version to the latest we published.
:::

:::hint{type="info"}
For more API or info on how it works, don't hesitate to contact our customer support.

The current version is in beta; every bug or problem during the integration will be valuable feedback for us. Please don't hesitate to contact us; your satisfaction is our great reward.
:::

## Requirements

We offer our SDK as a pre-compiled binary package as a XCFramework that you can add to your application. We support iOS versions >= 12.

:::hint{type="warning"}
The iOS PubConsent SDK is written in Swift so if your app is written in Objective-C, please make sure that the `Always Embed Swift Standard Libraries` flag is set to `YES`.
:::

## Add the SDK to your project

The package can be added using CocoaPods or manually.

### Using CocoaPods

:::hint{type="danger"}
Starting with upcoming releases, support for CocoaPods will be discontinued. **We strongly recommend migrating to Swift Package Manager (SPM)**, which is the official package management tool supported by Apple. SPM provides better integration with Xcode, improved stability, and ongoing support from the community.
For more details on the migration, please refer to Apple's official documentation or reach out to our support team.
:::

The package can be added using CocoaPods:

Xcode >= 12 (XCFramework)

1. If you haven't already, install the latest version of CocoaPods.
2. Add this line to your Podfile:

```sh
pod 'PubConsent', '3.0.3'
```

### Using Swift Package Manager

The iOS SDK is available through Swift Package Manager as a binary library. In order to integrate it into your iOS project follow the instructions below:

1. Open your Xcode project
2. Select your project in the navigator area
3. Select your project in the PROJECT section
4. Select the Package Dependencies
5. Click on the + button
6. Copy the package url [https://github.com/pubtech-ai/pubconsent-sdk-apple-os-spm](https://github.com/pubtech-ai/pubconsent-sdk-apple-os-spm) into the search bar
7. Select the pubconsent-ios-sdk package from the list
8. Click on Add Package
9. From the Choose Package Products for the pubconsent-ios-sdk screen click on Add Package

### Manually

The package can also be added manually as explained below:

1. Download and unzip the latest version of our framework for Xcode >= 12: [https://cdn.pubtech.ai/pubconsent-sdk-for-publishers/pubconsent-3.0.3-xcframework.zip](https://cdn.pubtech.ai/pubconsent-sdk-for-publishers/pubconsent-3.0.3-xcframework.zip)
2. In Xcode, select your project.
3. Then, select your app target.
4. Click on the General tab.
5. Scroll down to the Embedded binaries section.
6. From finder, drag the PubConsent.framework file into the Embedded binaries section.
7. Make sure the Copy items if needed box is checked and click on finish.

### Consent sharing with WebView

If you need to reuse the consent collected through our SDK in a WebView pointing to your website, you can refer to the documentation [Consent sharing with WebView (App)](docId\:ZooPMmq_MqSabXypt4cro) .

## Initialize the SDK

The initialization process will prepare the SDK for interactions with the user and your application.
It is important to launch the SDK initialization as soon as possible since this makes possible for the CMP to be showed as soon as possible to the user to ask consent if necessary.

In the AppDelegate, make sure to import the PubConsent module, then call the initialize method and pass your API key:

```swift
import SwiftUI
import PubConsentC

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        let consentReadyHandler = ConsentReadyHandler()
        let closeUIHandler = CloseUIHandler()
        let openUIHandler = OpenUIHandler()
        let googleConsentModeHandler = GoogleConsentModeHandler()
        let errorHandler = ErrorHandler()

        let cmpCallbacks = CmpCallbacks(
            onConsentReadyCallback: consentReadyHandler,
            onCloseUICallback: closeUIHandler,
            onCmpUIOpenCallback: openUIHandler,
            onErrorCallback: errorHandler,
            onGoogleConsentModeCallback: googleConsentModeHandler
        )
        let parameters = CmpConfig(
            id: "your-id", appName: "your-app-name", debug: false, callbacks: cmpCallbacks
        )
        PubConsentCMP.shared.configure(cmpConfiguration: parameters)

        return true
    }
}

@main
struct YourAppName: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}


class ConsentReadyHandler: OnConsentReadyCallback {
    func onConsentReady(consentApiInstance: any PubConsent.ConsentApiInterface) {
        if (consentApiInstance.getCmpType() == CmpType.TCF_V2_GDPR) {
            if let apiInstance = consentApiInstance as? TCFGDPRConsentApi {
                print("Google Consent Status \(apiInstance.isVendorConsentEnabled(vendorId: 755))")
                print("Google Consent Mode ad_personalization granted? \(apiInstance.getGoogleConsentMode()[GoogleConsentModeType.ad_personalization] == .granted)")
            } else {
                print("Contact Pubtech since there is some unexpected problem (This can't happen but it's better to track every exception.")
            }
        }
        if (consentApiInstance.getCmpType() == CmpType.GOOGLE_CONSENT_MODE) {
            if let apiInstance = consentApiInstance as? GCMConsentApi {
                print("Google Consent Mode ad_personalization granted? \(apiInstance.getGoogleConsentMode()[GoogleConsentModeType.ad_personalization] == .granted)")
            }
        }
    }
}

class CloseUIHandler: OnCloseUICallback {
    func onCmpUIClosed() {
        print("CMP UI has been closed.")
    }
}

class OpenUIHandler: OnOpenUICallback {
    func onCmpUIOpen() {
        print("CMP UI has been opened.")
    }
}

class ErrorHandler: OnErrorCallback {
    func onError(message: String) {
        print("Error occurred: \(message)")
    }
}
```

## Wrapping UIViewController

Note: the setupUI method should be called only from your main/entry UIViewController which in most cases should be once per app launch.

In order for the SDK to be able to display UI elements and interact with the user, you must provide a reference to your main UIViewController. Make sure to import the PubConsent module and call the setupUI method in Swift, setupUIWithContainerController in Objective-C, of the SDK in the viewDidLoad method of your main UIViewController:

```swift
import SwiftUI

struct ViewControllerRepresentable: UIViewControllerRepresentable {
    let viewController = UIViewController()
    
    func makeUIViewController(context: Context) -> some UIViewController {
        return viewController
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        // No implementation needed. Nothing to update.
    }
}
```

## Call the UI directly

In order to make everything work and to display UI elements you must execute the following line of code:
`PubConsentCMP.shared.setupUI(containerController: viewControllerRepresentable.viewController)`

The following is an example of usage:

```swift
import SwiftUI
import PubConsent
import WebKit
import UIKit

struct ContentView: View {
    private let viewControllerRepresentable = ViewControllerRepresentable()
    
    var body: some View {
        ZStack {
            VStack {
                HStack(alignment: .bottom, content: {
                    VStack(alignment: .leading, content: {
                        Text("PubConsent CMP").font(.title)
                        Text("iOS").font(.title).colorInvert()
                    })
                })
                
                VStack(spacing: 30) {
                    Text("Demo Actions:").font(.headline)
                    
                    Button("Open CMP") {
                        PubConsentCMP.shared.showNotice()
                    }
                    Button("Print Info") {
                        print("Google vendor is enabled? \(PubConsentCMP.shared.isVendorConsentEnabled(vendorId: 755))")
                    }
                }
                .padding(.top, 100)
                .background {
                    viewControllerRepresentable
                        .frame(width: .zero, height: .zero)
                }
                .onAppear {
                    Task {
                        PubConsentCMP.shared.setupUI(containerController: viewControllerRepresentable.viewController)
                    }
                }
            }
        }
    }
}

#Preview {
    ContentView()
}
```

### Integrate with App Tracking Transparency

For more information on how to integrate the PubConsent CMP with ATT, you can refer to the relevant [App Tracking Transparency (iOS 14.5+)](docId\:G_pMXBpsw-ShDaWu4KqDS).

## Google Consent Mode Integration (v2)

Google Consent Mode allows you to adjust the behavior of Google tags and the Firebase SDK based on the user's consent status. To comply with Google's updated EU user consent policy, the PubTech CMP supports the four mandatory parameters: ad\_storage, analytics\_storage, ad\_user\_data, and ad\_personalization.

**1. Set Default Consent States**

&#x20;Before the CMP is initialized, you should define the default consent states in your app's configuration files. (Info.plist). Add the following keys to your Info.plist

```xml
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS</key> <false/>
```

**2. Synchronize Consent with Firebase SDK**

You must update the Firebase SDK whenever the PubTech CMP captures or updates user consent. Use the onConsentReady  callback to map PubTech's consent types to Firebase.

```swift
import FirebaseAnalytics

class ConsentReadyHandler: OnConsentReadyCallback {
    func ononConsentReady(consentApiInstance: any PubConsent.ConsentApiInterface) {
        let gcm = consentApiInstance.getGoogleConsentMode()

        Analytics.setConsent([
            .analyticsStorage: gcm[.analytics_storage] == .granted ? .granted : .denied,
            .adStorage: gcm[.ad_storage] == .granted ? .granted : .denied,
            .adUserData: gcm[.ad_user_data] == .granted ? .granted : .denied,
            .adPersonalization: gcm[.ad_personalization] == .granted ? .granted : .denied
        ])
    }
}
```

**3. Verification** To verify that signals are being sent correctly:

- **iOS:** Add `-FIRAnalyticsVerboseLoggingEnabled` to your app's launch arguments in Xcode.

## SDK APIs

The following is the struct you must initialize and provide it to the configure method `PubConsent.shared.configure`

### Struct: `CmpConfig`

**Description**:

Represents the configuration settings for the Consent Management Platform (CMP).

**Properties**:

- `id`: A string representing the CMP ID (get if from PubTech Dashboard).
- `appName`: A string representing the name of the application.
- `debug`: A boolean indicating whether the CMP is in debug mode.
- `callbacks`: An optional instance of `CmpCallbacks` containing callback functions.

### Methods:

- `init(id:appName:debug:callbacks:)`: Initializes a new instance of `CmpConfig`.

### Struct: `CmpCallbacks`

**Description**:

Contains callback functions for the primary PubConsentCMP events.

**Properties**:

- `onConsentReadyCallback`: A callback function called when consent is ready.
- `onCloseUICallback`: A callback function called when the CMP UI is closed.
- `onCmpUIOpenCallback`: A callback function called when the CMP UI is opened.
- `onErrorCallback`: A callback function called when an error occurs.
- `onGoogleConsentModeCallback`: A callback function called when Google consent mode is updated.

## PubConsent `ConsentApiInterface`

Using the API exposed through `onConsentReadyCallback`, you can check which of the following implementations are available using the getCmpType() method (this choice depends on the configuration saved through the PubConsent configurator).

Below, we present the APIs for each CMP Type we offer. The following methods are accessible via the instance `consentApiInstance: any PubConsent.ConsentApiInterface`, available as a parameter in the callback: `onConsentReadyCallback`.

### API available for CmpType.TCF\_V2\_GDPR

### Method: `isVendorConsentEnabled(vendorId:)`

**Description**: This method checks whether consent is enabled for a specific vendor.

**Parameters**:

- `vendorId`: An integer representing the ID of the vendor.

**Returns**:

- `Bool`: Returns `true` if consent is enabled for the specified vendor, otherwise `false`.

### Method: `isPurposeConsentEnabled(purposeId:)`

**Description**: This method checks whether consent is enabled for a specific purpose.

**Parameters**:

- `purposeId`: An integer representing the ID of the purpose.

**Returns**:

- `Bool`: Returns `true` if consent is enabled for the specified purpose, otherwise `false`.

### Method: `isFeatureCookiesEnabled()`

**Description**: This method checks whether consent is enabled for feature cookies.

**Returns**:

- `Bool`: Returns `true` if consent is enabled for feature cookies, otherwise `false`.

### Method: `isUserExperienceCookiesEnabled()`

**Description**: This method checks whether consent is enabled for user experience cookies.

**Returns**:

- `Bool`: Returns `true` if consent is enabled for user experience cookies, otherwise `false`.

### Method: `isMeasurementCookiesEnabled()`

**Description**: This method checks whether consent is enabled for measurement cookies.

**Returns**:

- `Bool`: Returns `true` if consent is enabled for measurement cookies, otherwise `false`.

### Method: `getGoogleConsentMode()`

**Description**: This method retrieves the consent mode status for Google services.

**Returns**:

- `[GoogleConsentModeType: GoogleConsentModeStatus]?`: Returns a dictionary containing the consent mode status for different Google services. Returns `nil` if the consent mode information is not available.

### API available for CmpType.GOOGLE\_CONSENT\_MODE

The following methods are accessible through by using the instance provided on the `onConsentReadyCallback`.

### Method: `getGoogleConsentMode()`

**Description**: This method retrieves the consent mode status for Google services.

**Returns**:

- `[GoogleConsentModeType: GoogleConsentModeStatus]?`: Returns a dictionary containing the consent mode status for different Google services. Returns `nil` if the consent mode information is not available.

### PubConsent  CMP Shared &#x4D;***ethods***

The following methods are accessible through by using the `PubConsent.shared` instance.

### Method: `setUserRejectedAll(containerController: viewControllerRepresentable.viewController)`

**Description**:This method will be used for app tracking transparency (ATT) integration. Instead of calling the `setupUI` method when the ATT state is `denied`, your app code should execute this method if you need to set everything in the CMP to denied, otherwise you can also choose to have no consent expressed at all.

### Method: `disableCmpPopup()`

**Description**: This method is going to be used for the App Tracking Transparency (ATT) integration. When the CMP is already showed to the user and the ATT is denied you can disable the CMP popup by hiding it.

### Method: `enableCmpPopup(containerController: UIViewController)`

**Description**: This method is going to be used for the App Tracking Transparency (ATT) integration. When the ATT is granted you can enable the CMP by calling this method.

### Metodo: `resetUserPreferences()`

**Descrizione**: This method when called delete all the user preferences relative to the CMP consents.
