Skip to main content

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.

Create Targeting

Learn how to create audience targeting in the console

2. Set User ID

You must set the user identifier before rendering ads.
import AdropAds

// Set user ID after login
Adrop.setUID("user_id")
Set the UID before entering the ad placement for targeting ads to work correctly.

3. Set User Properties

Setting user attributes enables more precise targeting.
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")
Property values only support single values (String, Int, Bool). Arrays or dictionaries are not supported.

Built-in Properties

The SDK provides predefined keys for commonly used attributes.

AdropKey

KeyDescriptionValue Type
AdropKey.GENDERGenderAdropValue.AdropGender
AdropKey.AGEAgeInt
AdropKey.BIRTHDate of birthString (YYYY, YYYYMM, YYYYMMDD)

AdropValue

Predefined values for gender:
ValueDescription
AdropValue.AdropGender.MALEMale
AdropValue.AdropGender.FEMALEFemale
AdropValue.AdropGender.OTHEROther
AdropValue.UNKNOWNUnknown
// 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

Custom Properties

You can set additional properties registered in the console. All custom property keys are strings, and values support String, Int, and Bool types.
// 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)

// Boolean values
AdropMetrics.setProperty(key: "is_subscribed", value: true)
AdropMetrics.setProperty(key: "newsletter_opt_in", value: false)
Custom properties must be registered in the console before use.

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, and Bool are available.
  • Pre-registration required: Custom properties must be registered in the console first.
// ❌ 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 Logging

You can log user behavior as events for more precise targeting.
import AdropAds

// Event without parameters
AdropMetrics.logEvent(name: "tutorial_complete")

// Event with parameters
AdropMetrics.logEvent(
    name: "purchase",
    params: [
        "item_id": "SKU_12345",
        "price": 9.99,
        "currency": "USD"
    ]
)

// Game event example
AdropMetrics.logEvent(
    name: "level_complete",
    params: [
        "level": 5,
        "score": 1500,
        "time_spent": 180
    ]
)

Common Event Examples

// App events
AdropMetrics.logEvent(name: "app_open")
AdropMetrics.logEvent(name: "tutorial_begin")
AdropMetrics.logEvent(name: "tutorial_complete")

// E-commerce events
AdropMetrics.logEvent(name: "view_item", params: ["item_id": "PROD_123"])
AdropMetrics.logEvent(name: "add_to_cart", params: ["item_id": "PROD_123", "quantity": 2])
AdropMetrics.logEvent(name: "begin_checkout", params: ["value": 49.99])
AdropMetrics.logEvent(name: "purchase", params: ["transaction_id": "T12345", "value": 49.99])

// Content events
AdropMetrics.logEvent(name: "view_article", params: ["article_id": "A123", "category": "tech"])
AdropMetrics.logEvent(name: "share_content", params: ["content_type": "article", "item_id": "A123"])

// Game events
AdropMetrics.logEvent(name: "level_start", params: ["level": 1])
AdropMetrics.logEvent(name: "level_complete", params: ["level": 1, "score": 1000])
AdropMetrics.logEvent(name: "unlock_achievement", params: ["achievement_id": "first_win"])

Contextual Targeting

You can target ads based on content or screen context.

1. Create Targeting

First, create contextual targeting in the Ad Control console.

Create Contextual Targeting

Learn how to create contextual targeting in the console

2. Set Value on Ad Placement

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

let banner = AdropBanner(unitId: "YOUR_UNIT_ID")
banner.contextId = "sport"  // Set context ID
banner.load()

Native Ads

import AdropAds

class ViewController: UIViewController {
    private var adLoader: AdropNativeAdLoader?

    func loadAd() {
        adLoader = AdropNativeAdLoader(unitId: "YOUR_UNIT_ID")
        adLoader?.contextId = "tech"  // Set context ID
        adLoader?.delegate = self
        adLoader?.loadAd()
    }
}

Interstitial Ads

import AdropAds

class ViewController: UIViewController {
    private var interstitial: AdropInterstitialAd?

    func loadAd() {
        interstitial = AdropInterstitialAd(unitId: "YOUR_UNIT_ID")
        interstitial?.contextId = "news"  // Set context ID
        interstitial?.delegate = self
        interstitial?.load()
    }
}

Rewarded Ads

import AdropAds

class ViewController: UIViewController {
    private var rewarded: AdropRewardedAd?

    func loadAd() {
        rewarded = AdropRewardedAd(unitId: "YOUR_UNIT_ID")
        rewarded?.contextId = "game"  // Set context ID
        rewarded?.delegate = self
        rewarded?.load()
    }
}

Dynamic Context Setting

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

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

    override func viewDidLoad() {
        super.viewDidLoad()

        banner = AdropBanner(unitId: "YOUR_UNIT_ID")

        // Set context based on article category
        if let category = articleCategory {
            banner?.contextId = category  // "sport", "tech", "business", etc.
        }

        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

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

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)

        // Log app start event
        AdropMetrics.logEvent(name: "app_open")

        return true
    }
}

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

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

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

    func completePurchase() {
        // Purchase complete event
        AdropMetrics.logEvent(
            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

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() {
        banner = AdropBanner(unitId: "YOUR_UNIT_ID")

        // Set article category as context ID
        if let category = article?.category {
            banner?.contextId = category
        }

        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() {
        // Log article view event
        if let article = article {
            AdropMetrics.logEvent(
                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.
// 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.
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. Log Meaningful Events

Only log important user actions as events.
// ✅ Good examples: Meaningful actions
AdropMetrics.logEvent(name: "purchase", params: ["value": 99.99])
AdropMetrics.logEvent(name: "level_complete", params: ["level": 10])
AdropMetrics.logEvent(name: "tutorial_complete")

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

4. Context ID Consistency

Context IDs must exactly match the values registered in the console.
// ✅ Good examples: Clear and consistent IDs
banner?.contextId = "sport"
banner?.contextId = "tech"
banner?.contextId = "business"

// ❌ Bad examples: Inconsistent or ambiguous IDs
banner?.contextId = "Sport"  // Case mismatch
banner?.contextId = "technology"  // Different from console value
banner?.contextId = "category_1"  // Unclear meaning

Next Steps