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

# Contextual Data

> Real-time content-based segmentation for privacy-friendly targeting

export const ContextualVsBehavioralTable = () => <table>
    <thead>
      <tr>
        <th>Aspect</th>
        <th>Behavioral Cohorts</th>
        <th>Contextual Cohorts</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><strong>Based on</strong></td>
        <td>User history</td>
        <td>Current content</td>
      </tr>
      <tr>
        <td><strong>Speed</strong></td>
        <td>Minutes to hours</td>
        <td>Real-time</td>
      </tr>
      <tr>
        <td><strong>Persistence</strong></td>
        <td>Long-term</td>
        <td>Session/page</td>
      </tr>
      <tr>
        <td><strong>Privacy</strong></td>
        <td>Requires user profile</td>
        <td>No profiling needed</td>
      </tr>
      <tr>
        <td><strong>Accuracy</strong></td>
        <td>Improves over time</td>
        <td>Immediate</td>
      </tr>
      <tr>
        <td><strong>Use Case</strong></td>
        <td>Audience targeting</td>
        <td>Content alignment</td>
      </tr>
    </tbody>
  </table>;

export const ContextualPrivacy = () => <>
    <p>Contextual Cohorts operate entirely on page-level data, requiring no user consent. This enables publishers to monetize inventory from users who haven't consented to data collection, expanding addressable inventory while maintaining privacy compliance.</p>
    <p>Key privacy benefits:</p>
    <ul>
      <li><strong>No user data processing</strong> - Targets content, not user behavior</li>
      <li><strong>No consent required</strong> - Works for all users regardless of consent status</li>
      <li><strong>No cross-site tracking</strong> - Only analyzes current page content</li>
      <li><strong>Cookie-less</strong> - Works without third-party cookies or persistent identifiers</li>
    </ul>
  </>;

export const ContextualOverview = () => <>
    <p><strong>Contextual Cohorts</strong> enable publishers to target ads based on contextual data derived from page content without processing or storing any user data. Since no user consent is required, Contextual Cohorts allow publishers to reach users who have not given consent and cannot be targeted with behavioral data today.</p>
    <p>Contextual Cohorts work by analyzing page-level signals such as automated content classifications, editorial metadata, and affinity scores from consented users. This enables publishers to create a differentiated contextual targeting offering that combines the precision of content understanding with the unique insights from their first-party data.</p>
  </>;

Contextual data enables real-time content-based segmentation without relying on historical user behavior. The SDK analyzes content users are viewing and generates contextual cohorts instantly.

<CardGroup cols={3}>
  <Card title="How It Works" href="#how-it-works" icon="gear" />

  <Card title="Implementation" href="#implementation" icon="code" />

  <Card title="Ad Targeting" href="#in-ad-requests" icon="bullseye" />
</CardGroup>

## Overview

<ContextualOverview />

In the iOS SDK, contextual cohorts are generated in real-time when you track pages or videos with URLs. The SDK automatically includes these cohorts in ad requests alongside behavioral cohorts.

## Requirements

* **SDK Version:** 2.0.0 or higher
* **Platform:** iOS 12.0+ / tvOS 12.0+
* **Feature Enablement:** Contact your Customer Success Manager

<Info>
  **Feature Activation Required:** Contextual content classification must be enabled by Permutive for your workspace. Please contact your Customer Success Manager if you'd like to use this feature.
</Info>

## How It Works

<Steps>
  <Step title="Track page with URL">
    Use `PageTracker` with a content URL
  </Step>

  <Step title="Content analyzed">
    Permutive analyzes the content at the URL (page title, main text, keywords, IAB categories, sentiment)
  </Step>

  <Step title="Contextual cohorts generated">
    Content-based segments are created in real-time
  </Step>

  <Step title="Automatic activation">
    Contextual cohorts automatically included in ad requests
  </Step>
</Steps>

***

## Implementation

### Page Tracking with Contextual Data

Simply include URLs when tracking pages - contextual analysis happens automatically:

<CodeGroup>
  ```swift Swift theme={"dark"}
  import UIKit
  import Permutive_iOS

  class ArticleViewController: UIViewController {
      private var pageTracker: PageTrackerProtocol?

      override func viewDidLoad() {
          super.viewDidLoad()

          // Create event properties
          let properties = try? EventProperties([
              "category": "automotive",
              "subcategory": "electric_vehicles",
              "author": "Jane Smith"
          ])

          // Track page with URL - contextual analysis automatic
          let context = Context(
              title: "Complete Guide to Electric Vehicles",
              url: URL(string: "https://example.com/articles/electric-vehicle-guide"),
              referrer: URL(string: "https://example.com/automotive")
          )

          pageTracker = try? Permutive.shared.createPageTracker(
              properties: properties,
              context: context
          )
      }

      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
          try? pageTracker?.resume()
      }

      override func viewDidDisappear(_ animated: Bool) {
          super.viewDidDisappear(animated)
          pageTracker?.pause()
      }

      deinit {
          pageTracker?.stop()
      }
  }
  ```

  ```objectivec Objective-C theme={"dark"}
  #import "ArticleViewController.h"
  @import Permutive_iOS;

  @interface ArticleViewController ()
  @property (nonatomic, strong) NSObject<PermutivePageTrackerProtocol> *pageTracker;
  @end

  @implementation ArticleViewController

  - (void)viewDidLoad {
      [super viewDidLoad];

      // Create event properties
      NSError *error = nil;
      PermutiveEventProperties *properties = [[PermutiveEventProperties alloc]
          init:@{
              @"category": @"automotive",
              @"subcategory": @"electric_vehicles",
              @"author": @"Jane Smith"
          }
          error:&error];

      // Track page with URL - contextual analysis automatic
      PermutiveContext *context = [[PermutiveContext alloc]
          initWithTitle:@"Complete Guide to Electric Vehicles"
          url:[NSURL URLWithString:@"https://example.com/articles/electric-vehicle-guide"]
          referrer:[NSURL URLWithString:@"https://example.com/automotive"]];

      self.pageTracker = [Permutive.shared
          createPageTrackerWithProperties:properties
          context:context
          error:&error];
  }

  - (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      [self.pageTracker resumeAndReturnError:nil];
  }

  - (void)viewDidDisappear:(BOOL)animated {
      [super viewDidDisappear:animated];
      [self.pageTracker pause];
  }

  - (void)dealloc {
      [self.pageTracker stop];
  }

  @end
  ```
</CodeGroup>

***

## Accessing Contextual Cohorts

Contextual cohorts are automatically included in activations with special keys:

### In Current Activations

<CodeGroup>
  ```swift Swift theme={"dark"}
  let activations = Permutive.shared.activations

  // Google Ad Manager contextual cohorts
  let gamContextual = activations["dfp_contextual"] ?? []
  // Example: ["automotive_ev", "automotive_reviews", "tech_innovation"]

  // Xandr/AppNexus contextual cohorts
  let xandrContextual = activations["appnexus_adserver_contextual"] ?? []

  // Log contextual cohorts
  print("GAM contextual cohorts: \(gamContextual)")
  ```

  ```objectivec Objective-C theme={"dark"}
  NSDictionary *activations = [Permutive.shared activations];

  // Google Ad Manager contextual cohorts
  NSArray *gamContextual = activations[@"dfp_contextual"] ?: @[];

  // Xandr/AppNexus contextual cohorts
  NSArray *xandrContextual = activations[@"appnexus_adserver_contextual"] ?: @[];

  NSLog(@"GAM contextual cohorts: %@", gamContextual);
  ```
</CodeGroup>

### In Ad Requests

Contextual cohorts are automatically included when using `googleCustomTargeting`:

<CodeGroup>
  ```swift Swift theme={"dark"}
  // Contextual cohorts automatically added with key "prmtvctx"
  let adRequest = GAMRequest()
  adRequest.customTargeting = Permutive.shared.googleCustomTargeting(
      adTargetable: pageTracker  // Include PageTracker for view ID
  )
  bannerView.load(adRequest)

  // The resulting ad request includes:
  // - permutive: ["123", "456"]           // Behavioral cohorts
  // - prmtvctx: ["cabf", "cabc", "bzwu"]  // Contextual cohorts
  // - puid: "user_id"
  // - ptime: "timestamp"
  // - prmtvvid: "view_id"
  ```

  ```objectivec Objective-C theme={"dark"}
  // Contextual cohorts automatically added
  GAMRequest *adRequest = [GAMRequest request];
  adRequest.customTargeting = [Permutive.shared
      googleCustomTargetingWithAdTargetable:self.pageTracker];
  [self.bannerView loadRequest:adRequest];
  ```
</CodeGroup>

***

## Performance Considerations

### Content Analysis Timing

* **First analysis:** May take 1-2 seconds for initial content fetch and analysis
* **Cached results:** Subsequent views of the same URL use cached analysis
* **Background processing:** Analysis happens asynchronously, doesn't block UI
* **Network required:** Content classification requires network connectivity

### Best Practices for Performance

<CodeGroup>
  ```swift Swift theme={"dark"}
  // ✅ Good: Create PageTracker early, analysis starts immediately
  override func viewDidLoad() {
      super.viewDidLoad()

      // Start tracking (and analysis) as early as possible
      pageTracker = try? Permutive.shared.createPageTracker(
          properties: properties,
          context: context
      )

      // Load your content
      loadArticleContent()
  }
  ```

  ```swift Swift theme={"dark"}
  // ❌ Avoid: Delaying page tracking
  override func viewDidLoad() {
      super.viewDidLoad()

      loadArticleContent()

      // Tracking delayed - contextual cohorts may not be ready for early ads
      DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
          self.pageTracker = try? Permutive.shared.createPageTracker(...)
      }
  }
  ```
</CodeGroup>

***

## Privacy and Compliance

### Privacy-Friendly Targeting

<ContextualPrivacy />

### Data Sent for Analysis

When tracking a page with a URL:

* **URL** - The page URL for content fetching
* **Title** - Page title (if provided)
* **No PII** - No personal information sent for classification

The URL should be **publicly accessible** for content analysis to work.

***

## Error Handling

### Classification Failures

Contextual classification may fail if:

* URL is not publicly accessible
* Content is behind a paywall or login
* Network connectivity issues
* Server-side analysis errors

**The SDK handles failures gracefully:**

<CodeGroup>
  ```swift Swift theme={"dark"}
  // If contextual classification fails:
  // 1. Behavioral cohorts still work
  // 2. Events still tracked
  // 3. No error surfaced to app
  // 4. Contextual activations will be empty

  let contextualCohorts = Permutive.shared.activations["dfp_contextual"] ?? []

  if contextualCohorts.isEmpty {
      // This is OK - may be:
      // - Feature not enabled
      // - Classification in progress
      // - Classification failed
      // - No URL tracked yet

      // Behavioral targeting still works
      let behavioralCohorts = Permutive.shared.activations["dfp"] ?? []
  }
  ```

  ```objectivec Objective-C theme={"dark"}
  NSArray *contextualCohorts = [Permutive.shared activations][@"dfp_contextual"] ?: @[];

  if (contextualCohorts.count == 0) {
      // Behavioral targeting still works
      NSArray *behavioralCohorts = [Permutive.shared activations][@"dfp"] ?: @[];
  }
  ```
</CodeGroup>

### Debugging Classification

Enable debug logging to see classification status:

```swift theme={"dark"}
options.logModes = LogMode.all

// Look for logs like:
// Permutive: [info] Contextual classification requested for URL: https://...
// Permutive: [info] Contextual cohorts received: [cohort1, cohort2, ...]
// Permutive: [error] Contextual classification failed: <reason>
```

***

## Use Cases

### Content-Aligned Advertising

<CodeGroup>
  ```swift Swift theme={"dark"}
  class ArticleViewController: UIViewController {
      private var pageTracker: PageTrackerProtocol?

      override func viewDidLoad() {
          super.viewDidLoad()

          // Track article page
          let context = Context(
              title: article.title,
              url: URL(string: article.url),
              referrer: nil
          )
          pageTracker = try? Permutive.shared.createPageTracker(
              properties: nil,
              context: context
          )
      }

      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
          try? pageTracker?.resume()

          // Load ad - contextual cohorts automatically included
          loadAd()
      }

      private func loadAd() {
          // Contextual cohorts ensure ad is relevant to article content
          let adRequest = GAMRequest()
          adRequest.customTargeting = Permutive.shared.googleCustomTargeting(
              adTargetable: pageTracker
          )
          bannerView.load(adRequest)
      }
  }
  ```

  ```objectivec Objective-C theme={"dark"}
  - (void)viewDidLoad {
      [super viewDidLoad];

      PermutiveContext *context = [[PermutiveContext alloc]
          initWithTitle:self.article.title
          url:[NSURL URLWithString:self.article.url]
          referrer:nil];

      self.pageTracker = [Permutive.shared
          createPageTrackerWithProperties:nil
          context:context
          error:nil];
  }

  - (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      [self.pageTracker resumeAndReturnError:nil];
      [self loadAd];
  }

  - (void)loadAd {
      GAMRequest *adRequest = [GAMRequest request];
      adRequest.customTargeting = [Permutive.shared
          googleCustomTargetingWithAdTargetable:self.pageTracker];
      [self.bannerView loadRequest:adRequest];
  }
  ```
</CodeGroup>

### Contextual + Behavioral Targeting

Combine contextual and behavioral cohorts for powerful targeting:

```swift theme={"dark"}
let activations = Permutive.shared.activations

// Behavioral: User interests over time
let behavioral = activations["dfp"] ?? []
// Example: ["sports_enthusiast", "premium_subscriber"]

// Contextual: Current content
let contextual = activations["dfp_contextual"] ?? []
// Example: ["sports_soccer", "sports_worldcup"]

// Both automatically included in ad requests
let adRequest = GAMRequest()
adRequest.customTargeting = Permutive.shared.googleCustomTargeting(
    adTargetable: pageTracker
)

// Ad platform receives:
// - permutive: ["sports_enthusiast", "premium_subscriber"]
// - prmtvctx: ["sports_soccer", "sports_worldcup"]
//
// Result: Highly targeted ad for soccer content to a sports enthusiast
```

***

## Contextual vs. Behavioral Cohorts

<ContextualVsBehavioralTable />

In the SDK, contextual cohorts use activation keys `dfp_contextual` and `appnexus_adserver_contextual`, while behavioral cohorts use `dfp` and `appnexus_adserver`.

### When to Use Each

**Use Behavioral Cohorts When:**

* Building long-term audience segments
* Retargeting campaigns
* Personalization based on user history
* Lookalike modeling

**Use Contextual Cohorts When:**

* Real-time content alignment needed
* Privacy regulations are strict
* New users without history
* Brand safety is critical
* Cookie-less environment

**Use Both When:**

* Maximum targeting precision needed
* Combining user intent (contextual) with user interests (behavioral)
* Premium inventory requires both signals

***

## tvOS Considerations

<Info>
  **tvOS Note:** Contextual data works identically on tvOS. Provide URLs in the Context when creating PageTrackers for content analysis.
</Info>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="No contextual cohorts appearing">
    **Problem:** `dfp_contextual` is empty or not present.

    **Possible Causes & Solutions:**

    1. **Feature not enabled**
       * Contact Customer Success Manager to enable

    2. **SDK version too old**
       * Update to SDK 2.0.0+

    3. **No URL tracked**
       * Ensure you're using `PageTracker` with a Context that has a valid URL

    4. **Classification in progress**
       * First analysis may take 1-2 seconds
       * Check again after a moment

    5. **URL not accessible**
       * Ensure URL is publicly accessible
       * Remove authentication requirements for analysis

    6. **Network issues**
       * Check device connectivity
       * Look for network errors in logs
  </Accordion>

  <Accordion title="Classification taking too long">
    **Problem:** Contextual cohorts not appearing before ads load.

    **Solutions:**

    * Start page tracking earlier in view lifecycle
    * Consider delaying ad request slightly if contextual is critical
    * Use behavioral cohorts as fallback
  </Accordion>

  <Accordion title="Wrong contextual cohorts">
    **Problem:** Cohorts don't match content.

    **Possible Causes:**

    * URL points to different content than displayed
    * Content changed since classification
    * Cache from previous analysis

    **Solutions:**

    * Ensure URL matches actual content
    * Use unique URLs for different content
    * Wait for cache expiry or contact support to invalidate
  </Accordion>
</AccordionGroup>

***

## Best Practices

### Do

* Track pages with URLs as early as possible
* Use publicly accessible URLs
* Ensure URLs are stable and won't change
* Test with debug logging enabled
* Use unique URLs for different content
* Combine with behavioral targeting for best results

### Don't

* Use authentication-protected URLs
* Track pages without URLs (contextual won't work)
* Expect instant results (allow 1-2 seconds)
* Rely solely on contextual for returning users
* Use duplicate URLs for different content

***

## Related Documentation

<CardGroup cols={2}>
  <Card title="Cohorts and Activations" icon="users" href="/sdks/mobile/ios/core-concepts/cohorts-and-activations">
    Understanding user segmentation
  </Card>

  <Card title="Page Tracking" icon="file" href="/sdks/mobile/ios/features/page-tracking">
    PageTracker guide
  </Card>

  <Card title="Google Ad Manager" icon="google" href="/sdks/mobile/ios/integrations/google-ad-manager">
    GAM integration
  </Card>

  <Card title="Xandr Integration" icon="rectangle-ad" href="/sdks/mobile/ios/integrations/appnexus-xandr">
    AppNexus integration
  </Card>
</CardGroup>
