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

# Targeting Settings

> Learn how to set up audience targeting and contextual targeting.

## Overview

Adrop SDK supports two types of targeting:

* **Audience Targeting**: Target ads based on user attributes (gender, age, interests, etc.)
* **Contextual Targeting**: Target ads based on content or screen context

By utilizing targeting, you can show more relevant ads to users, and advertisers can effectively deliver ads to their desired audience.

***

## Audience Targeting

You can target ads based on user attributes.

### 1. Create Targeting

First, create audience targeting in the Ad Control console.

<Card title="Create Targeting" icon="bullseye" href="/targeting/audience">
  Learn how to create audience targeting in the console
</Card>

### 2. Set User ID

You must set the user identifier before rendering ads.

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  // Set user ID after login
  Adrop.setUID("user_id")
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  // Set user ID after login
  [Adrop setUID:@"user_id"];
  ```
</CodeGroup>

<Note>
  Set the UID before entering the ad placement for targeting ads to work correctly.
</Note>

### 3. Set User Properties

Setting user attributes enables more precise targeting.

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  // Set built-in properties
  AdropMetrics.setProperty(key: AdropKey.GENDER, value: AdropValue.AdropGender.MALE)
  AdropMetrics.setProperty(key: AdropKey.AGE, value: 30)
  AdropMetrics.setProperty(key: AdropKey.BIRTH, value: "19931225")

  // Set custom properties (must be registered in console)
  AdropMetrics.setProperty(key: "membership", value: "premium")
  AdropMetrics.setProperty(key: "interest_tech", value: true)
  AdropMetrics.setProperty(key: "last_purchase_date", value: "2024-01-15")
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  // Set built-in properties
  [AdropMetrics setPropertyWithKey:AdropKeyGENDER value:AdropValueAdropGenderMALE];
  [AdropMetrics setPropertyWithKey:AdropKeyAGE value:@30];
  [AdropMetrics setPropertyWithKey:AdropKeyBIRTH value:@"19931225"];

  // Set custom properties (must be registered in console)
  [AdropMetrics setPropertyWithKey:@"membership" value:@"premium"];
  [AdropMetrics setPropertyWithKey:@"interest_tech" value:@YES];
  [AdropMetrics setPropertyWithKey:@"last_purchase_date" value:@"2024-01-15"];
  ```
</CodeGroup>

<Note>The `setProperty()` method may have limited availability in Objective-C due to its `Encodable` parameter type. Use Swift for property configuration when possible.</Note>

<Warning>
  Property values only support single values (String, Int, Double, Bool). Arrays or dictionaries are not supported.
</Warning>

### Built-in Properties

The SDK provides predefined keys for commonly used attributes.

#### AdropKey

| Key               | Description   | Value Type                      |
| ----------------- | ------------- | ------------------------------- |
| `AdropKey.GENDER` | Gender        | AdropValue.AdropGender          |
| `AdropKey.AGE`    | Age           | Int                             |
| `AdropKey.BIRTH`  | Date of birth | String (YYYY, YYYYMM, YYYYMMDD) |

#### AdropValue

Predefined values for gender:

| Value                           | Description |
| ------------------------------- | ----------- |
| `AdropValue.AdropGender.MALE`   | Male        |
| `AdropValue.AdropGender.FEMALE` | Female      |
| `AdropValue.AdropGender.OTHER`  | Other       |
| `AdropValue.UNKNOWN`            | Unknown     |

<CodeGroup>
  ```swift Swift Example theme={null}
  // Set gender
  AdropMetrics.setProperty(key: AdropKey.GENDER, value: AdropValue.AdropGender.MALE)
  AdropMetrics.setProperty(key: AdropKey.GENDER, value: AdropValue.AdropGender.FEMALE)
  AdropMetrics.setProperty(key: AdropKey.GENDER, value: AdropValue.AdropGender.OTHER)

  // Set age
  AdropMetrics.setProperty(key: AdropKey.AGE, value: 25)

  // Set date of birth
  AdropMetrics.setProperty(key: AdropKey.BIRTH, value: "1999")         // Year only
  AdropMetrics.setProperty(key: AdropKey.BIRTH, value: "199903")       // Year and month
  AdropMetrics.setProperty(key: AdropKey.BIRTH, value: "19990315")     // Full date
  ```

  ```objc Objective-C Example theme={null}
  // Set gender
  [AdropMetrics setPropertyWithKey:AdropKeyGENDER value:AdropValueAdropGenderMALE];
  [AdropMetrics setPropertyWithKey:AdropKeyGENDER value:AdropValueAdropGenderFEMALE];
  [AdropMetrics setPropertyWithKey:AdropKeyGENDER value:AdropValueAdropGenderOTHER];

  // Set age
  [AdropMetrics setPropertyWithKey:AdropKeyAGE value:@25];

  // Set date of birth
  [AdropMetrics setPropertyWithKey:AdropKeyBIRTH value:@"1999"];       // Year only
  [AdropMetrics setPropertyWithKey:AdropKeyBIRTH value:@"199903"];     // Year and month
  [AdropMetrics setPropertyWithKey:AdropKeyBIRTH value:@"19990315"];   // Full date
  ```
</CodeGroup>

### Custom Properties

You can set additional properties registered in the console. All custom property keys are strings, and values support String, Int, Double, and Bool types.

<CodeGroup>
  ```swift Swift theme={null}
  // String values
  AdropMetrics.setProperty(key: "membership", value: "premium")
  AdropMetrics.setProperty(key: "favorite_category", value: "electronics")

  // Integer values
  AdropMetrics.setProperty(key: "purchase_count", value: 5)
  AdropMetrics.setProperty(key: "loyalty_points", value: 1500)

  // Double values
  AdropMetrics.setProperty(key: "average_purchase", value: 49.99)

  // Boolean values
  AdropMetrics.setProperty(key: "is_subscribed", value: true)
  AdropMetrics.setProperty(key: "newsletter_opt_in", value: false)

  // Remove a property by passing nil
  AdropMetrics.setProperty(key: "membership", value: nil)
  ```

  ```objc Objective-C theme={null}
  // String values
  [AdropMetrics setPropertyWithKey:@"membership" value:@"premium"];
  [AdropMetrics setPropertyWithKey:@"favorite_category" value:@"electronics"];

  // Integer values
  [AdropMetrics setPropertyWithKey:@"purchase_count" value:@5];
  [AdropMetrics setPropertyWithKey:@"loyalty_points" value:@1500];

  // Double values
  [AdropMetrics setPropertyWithKey:@"average_purchase" value:@49.99];

  // Boolean values
  [AdropMetrics setPropertyWithKey:@"is_subscribed" value:@YES];
  [AdropMetrics setPropertyWithKey:@"newsletter_opt_in" value:@NO];

  // Remove a property by passing nil
  [AdropMetrics setPropertyWithKey:@"membership" value:nil];
  ```
</CodeGroup>

<Warning>
  Custom properties must be registered in the console before use.
</Warning>

### Constraints

Note the following constraints when setting properties:

* **Single values only**: Arrays (`[String]`, `[Int]`) or dictionaries (`[String: Any]`) are not supported.
* **Supported types**: Only String, Int, Double, and Bool are available.
* **Key length**: Up to 64 characters.
* **Value length**: String values up to 256 characters.
* **Max properties**: Up to 256 properties per user.
* **Pre-registration required**: Custom properties must be registered in the console first.

```swift theme={null}
// ❌ Wrong usage (arrays/dictionaries)
AdropMetrics.setProperty(key: "interests", value: ["tech", "gaming"])  // Not supported
AdropMetrics.setProperty(key: "profile", value: ["age": 25])          // Not supported

// ✅ Correct usage
AdropMetrics.setProperty(key: "interest_tech", value: true)
AdropMetrics.setProperty(key: "interest_gaming", value: true)
AdropMetrics.setProperty(key: "age", value: 25)
```

***

## Event Tracking

Track user behavior events to build audiences based on user actions. Use `AdropMetrics.sendEvent()` to send events.

<Note>
  `logEvent()` is deprecated. Use `sendEvent()` instead.
</Note>

### Sending Events

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  // Simple event (no parameters)
  AdropMetrics.sendEvent(name: "app_open")

  // Event with parameters
  AdropMetrics.sendEvent(name: "view_item", params: [
      "item_id": "SKU-123",
      "item_name": "Widget",
      "item_category": "Electronics",
      "price": 29.99
  ])
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  // Simple event (no parameters)
  [AdropMetrics sendEventWithName:@"app_open" params:nil];

  // Event with parameters
  [AdropMetrics sendEventWithName:@"view_item"
                           params:@{
                               @"item_id": @"SKU-123",
                               @"item_name": @"Widget",
                               @"item_category": @"Electronics",
                               @"price": @29.99
                           }];
  ```
</CodeGroup>

### Multi-Item Events

For events involving multiple items (e.g., purchase, begin\_checkout), pass an array of dictionaries under the `"items"` key.

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  AdropMetrics.sendEvent(name: "purchase", params: [
      "tx_id": "tx_123",
      "currency": "KRW",
      "items": [
          ["item_id": "A", "item_name": "Product A", "price": 100, "quantity": 1],
          ["item_id": "B", "item_name": "Product B", "price": 200, "quantity": 2]
      ]
  ])
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  [AdropMetrics sendEventWithName:@"purchase"
                           params:@{
                               @"tx_id": @"tx_123",
                               @"currency": @"KRW",
                               @"items": @[
                                   @{@"item_id": @"A", @"item_name": @"Product A", @"price": @100, @"quantity": @1},
                                   @{@"item_id": @"B", @"item_name": @"Product B", @"price": @200, @"quantity": @2}
                               ]
                           }];
  ```
</CodeGroup>

### Supported Event Examples

| Event Name        | Description        | Common Parameters                           |
| ----------------- | ------------------ | ------------------------------------------- |
| `app_open`        | App opened         | —                                           |
| `sign_up`         | User signed up     | `method`                                    |
| `view_item`       | Viewed item        | `item_id`, `item_name`, `price`             |
| `add_to_cart`     | Added to cart      | `item_id`, `item_name`, `price`, `quantity` |
| `add_to_wishlist` | Added to wishlist  | `item_id`, `item_name`, `price`             |
| `begin_checkout`  | Began checkout     | `currency`, `items`                         |
| `purchase`        | Purchase completed | `tx_id`, `currency`, `items`                |
| `page_view`       | Page viewed        | `page_id`, `page_category`                  |
| `click`           | Element clicked    | `element_id`, `element_type`                |

<Note>
  * Event name must be 1–64 characters.
  * Parameter key must be 1–64 characters.
  * String parameter values are limited to 1024 characters.
  * Duplicate events with the same name and parameters are throttled within a 500ms window.
</Note>

### User Data Consent

You can control whether user data is sent to the server using `userDataConsent`. When set to `false`, property data is stored locally only, and events are not transmitted.

```swift theme={null}
// Check current consent status
let hasConsent = AdropMetrics.userDataConsent

// Set consent status
AdropMetrics.setUserDataConsent(true)
```

<Warning>
  When `userDataConsent` is `false`, targeting and event tracking will not function. Ensure consent is set to `true` before using `setProperty()` or `sendEvent()`.
</Warning>

***

## Contextual Targeting

You can target ads based on content or screen context.

### 1. Create Targeting

First, create contextual targeting in the Ad Control console.

<Card title="Create Contextual Targeting" icon="tags" href="/targeting/context">
  Learn how to create contextual targeting in the console
</Card>

### 2. Set Value on Ad Placement

Pass the Context ID set in the console when loading ads.

#### Banner Ads

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  // contextId is set via initializer (read-only property)
  let banner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "sport")
  banner.load()
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  // contextId is set via initializer
  AdropBanner *banner = [[AdropBanner alloc] initWithUnitId:@"YOUR_UNIT_ID" contextId:@"sport"];
  [banner load];
  ```
</CodeGroup>

#### Native Ads

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  class ViewController: UIViewController {
      private var nativeAd: AdropNativeAd?

      func loadAd() {
          // contextId is set via initializer
          nativeAd = AdropNativeAd(unitId: "YOUR_UNIT_ID", contextId: "tech")
          nativeAd?.delegate = self
          nativeAd?.load()
      }
  }
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  @interface ViewController ()
  @property (nonatomic, strong) AdropNativeAd *nativeAd;
  @end

  @implementation ViewController

  - (void)loadAd {
      // contextId is set via initializer
      self.nativeAd = [[AdropNativeAd alloc] initWithUnitId:@"YOUR_UNIT_ID" contextId:@"tech"];
      self.nativeAd.delegate = self;
      [self.nativeAd load];
  }

  @end
  ```
</CodeGroup>

#### Interstitial Ads

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  class ViewController: UIViewController {
      private var interstitial: AdropInterstitialAd?

      func loadAd() {
          interstitial = AdropInterstitialAd(unitId: "YOUR_UNIT_ID")
          // Note: contextId is not available on InterstitialAd
          interstitial?.delegate = self
          interstitial?.load()
      }
  }
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  @interface ViewController ()
  @property (nonatomic, strong) AdropInterstitialAd *interstitial;
  @end

  @implementation ViewController

  - (void)loadAd {
      self.interstitial = [[AdropInterstitialAd alloc] initWithUnitId:@"YOUR_UNIT_ID"];
      // Note: contextId is not available on InterstitialAd
      self.interstitial.delegate = self;
      [self.interstitial load];
  }

  @end
  ```
</CodeGroup>

#### Rewarded Ads

<CodeGroup>
  ```swift Swift theme={null}
  import AdropAds

  class ViewController: UIViewController {
      private var rewarded: AdropRewardedAd?

      func loadAd() {
          rewarded = AdropRewardedAd(unitId: "YOUR_UNIT_ID")
          // Note: contextId is not available on RewardedAd
          rewarded?.delegate = self
          rewarded?.load()
      }
  }
  ```

  ```objc Objective-C theme={null}
  @import AdropAds;

  @interface ViewController ()
  @property (nonatomic, strong) AdropRewardedAd *rewarded;
  @end

  @implementation ViewController

  - (void)loadAd {
      self.rewarded = [[AdropRewardedAd alloc] initWithUnitId:@"YOUR_UNIT_ID"];
      // Note: contextId is not available on RewardedAd
      self.rewarded.delegate = self;
      [self.rewarded load];
  }

  @end
  ```
</CodeGroup>

### Dynamic Context Setting

You can set context dynamically based on the screen or content.

```swift theme={null}
import UIKit
import AdropAds

class ArticleViewController: UIViewController {
    private var banner: AdropBanner?
    var articleCategory: String?  // Article category

    override func viewDidLoad() {
        super.viewDidLoad()

        // contextId is set via initializer (read-only property)
        let contextId = articleCategory ?? ""
        banner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: contextId)

        banner?.delegate = self
        view.addSubview(banner!)
        banner?.load()
    }
}

// Usage example
let sportArticle = ArticleViewController()
sportArticle.articleCategory = "sport"

let techArticle = ArticleViewController()
techArticle.articleCategory = "tech"
```

### Context Setting in SwiftUI

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

struct ArticleView: View {
    let category: String

    var body: some View {
        VStack {
            Text("Article Content")

            // Set context dynamically based on category
            AdropBannerRepresented(
                unitId: "YOUR_UNIT_ID",
                contextId: category
            )
            .frame(width: 320, height: 100)
        }
    }
}

// Usage example
struct ContentView: View {
    var body: some View {
        TabView {
            ArticleView(category: "sport")
                .tabItem { Label("Sports", systemImage: "sportscourt") }

            ArticleView(category: "tech")
                .tabItem { Label("Tech", systemImage: "cpu") }

            ArticleView(category: "business")
                .tabItem { Label("Business", systemImage: "chart.line.uptrend.xyaxis") }
        }
    }
}
```

***

## Full Examples

### Audience Targeting Full Example

```swift theme={null}
import UIKit
import AdropAds

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // Initialize SDK
        Adrop.initialize(production: false)

        // Set UID after user login
        Adrop.setUID("user_12345")

        // Set basic user properties
        AdropMetrics.setProperty(key: AdropKey.GENDER, value: AdropValue.AdropGender.MALE)
        AdropMetrics.setProperty(key: AdropKey.AGE, value: 28)
        AdropMetrics.setProperty(key: AdropKey.BIRTH, value: "19960315")

        // Set custom properties
        AdropMetrics.setProperty(key: "membership", value: "premium")
        AdropMetrics.setProperty(key: "interest_tech", value: true)
        AdropMetrics.setProperty(key: "interest_sports", value: true)
        AdropMetrics.setProperty(key: "purchase_count", value: 15)

        // Send app start event
        AdropMetrics.sendEvent(name: "app_open")

        return true
    }
}

class ProductViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Product view event
        AdropMetrics.sendEvent(
            name: "view_item",
            params: [
                "item_id": "PROD_123",
                "category": "electronics",
                "price": 299.99
            ]
        )
    }

    @IBAction func addToCartTapped(_ sender: UIButton) {
        // Add to cart event
        AdropMetrics.sendEvent(
            name: "add_to_cart",
            params: [
                "item_id": "PROD_123",
                "quantity": 1,
                "price": 299.99
            ]
        )
    }

    func completePurchase() {
        // Purchase complete event
        AdropMetrics.sendEvent(
            name: "purchase",
            params: [
                "transaction_id": "T67890",
                "value": 299.99,
                "currency": "USD"
            ]
        )

        // Update purchase count
        let newPurchaseCount = 16
        AdropMetrics.setProperty(key: "purchase_count", value: newPurchaseCount)
    }
}
```

### Contextual Targeting Full Example

```swift theme={null}
import UIKit
import AdropAds

// News app example: Display different ads based on article category
class NewsArticleViewController: UIViewController {
    private var banner: AdropBanner?

    // Article info
    var article: Article?

    struct Article {
        let id: String
        let title: String
        let category: String  // "sport", "tech", "business", "entertainment"
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupBanner()
        loadArticle()
    }

    private func setupBanner() {
        // contextId is read-only — set via initializer
        let contextId = article?.category ?? ""
        banner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: contextId)

        banner?.delegate = self

        if let bannerView = banner {
            view.addSubview(bannerView)
            bannerView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
                bannerView.widthAnchor.constraint(equalToConstant: 320),
                bannerView.heightAnchor.constraint(equalToConstant: 100)
            ])
        }

        banner?.load()
    }

    private func loadArticle() {
        // Send article view event
        if let article = article {
            AdropMetrics.sendEvent(
                name: "view_article",
                params: [
                    "article_id": article.id,
                    "category": article.category
                ]
            )
        }
    }
}

extension NewsArticleViewController: AdropBannerDelegate {
    func onAdReceived(_ banner: AdropBanner) {
        print("Category '\(article?.category ?? "")' targeted ad loaded successfully")
    }

    func onAdFailedToReceive(_ banner: AdropBanner, _ errorCode: AdropErrorCode) {
        print("Ad load failed: \(errorCode)")
    }

    func onAdImpression(_ banner: AdropBanner) {
        print("Ad impression")
    }

    func onAdClicked(_ banner: AdropBanner) {
        print("Ad clicked")
    }
}

// Usage example
let sportArticle = NewsArticleViewController()
sportArticle.article = NewsArticleViewController.Article(
    id: "A123",
    title: "Premier League Match Results",
    category: "sport"
)

let techArticle = NewsArticleViewController()
techArticle.article = NewsArticleViewController.Article(
    id: "A124",
    title: "New AI Technology Announced",
    category: "tech"
)
```

***

## Best Practices

### 1. UID Setting Timing

Set the UID as soon as the user logs in.

```swift theme={null}
// On successful login
func didLoginSuccessfully(userId: String) {
    Adrop.setUID(userId)

    // Also set user properties
    AdropMetrics.setProperty(key: "is_logged_in", value: true)
}

// On logout
func didLogout() {
    Adrop.setUID("")  // Reset UID
    AdropMetrics.setProperty(key: "is_logged_in", value: false)
}
```

### 2. Maintain Property Consistency

Set user properties at app launch or whenever values change.

```swift theme={null}
class UserManager {
    func updateUserProfile(profile: UserProfile) {
        // Sync properties when profile info updates
        AdropMetrics.setProperty(key: AdropKey.AGE, value: profile.age)
        AdropMetrics.setProperty(key: "membership", value: profile.membershipLevel)
        AdropMetrics.setProperty(key: "interest_\(profile.mainInterest)", value: true)
    }
}
```

### 3. Send Meaningful Events

Only send important user actions as events.

```swift theme={null}
// ✅ Good examples: Meaningful actions
AdropMetrics.sendEvent(name: "purchase", params: ["value": 99.99])
AdropMetrics.sendEvent(name: "level_complete", params: ["level": 10])
AdropMetrics.sendEvent(name: "tutorial_complete")

// ❌ Bad examples: Excessive events
AdropMetrics.sendEvent(name: "button_tapped")  // Too generic
AdropMetrics.sendEvent(name: "scroll")         // Too frequent
```

### 4. Context ID Consistency

Context IDs must exactly match the values registered in the console.

```swift theme={null}
// ✅ Good examples: Clear and consistent IDs (set via initializer)
let sportBanner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "sport")
let techBanner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "tech")
let bizBanner = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "business")

// ❌ Bad examples: Inconsistent or ambiguous IDs
let banner1 = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "Sport")  // Case mismatch
let banner2 = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "technology")  // Different from console value
let banner3 = AdropBanner(unitId: "YOUR_UNIT_ID", contextId: "category_1")  // Unclear meaning
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Banner Ads" href="/sdk/ios/banner">
    Apply targeting to banner ads
  </Card>

  <Card title="Native Ads" href="/sdk/ios/native">
    Apply targeting to native ads
  </Card>

  <Card title="Create Audience Targeting" icon="bullseye" href="/targeting/audience">
    Create audience targeting in the console
  </Card>

  <Card title="Create Contextual Targeting" icon="tags" href="/targeting/context">
    Create contextual targeting in the console
  </Card>
</CardGroup>
