> Agents can also search and read this documentation through its [MCP server](https://platform-business.gitbook.io/adpie/~gitbook/mcp).

# 시작하기

애드파이 SDK를 연동하기에 앞서 우선 되어야 하는 작업입니다.

### 1: 어드민 계정 생성

* 애드파이 홈페이지 회원 가입 버튼을 눌러 계정 생성을 진행합니다.
* <https://my.adpies.com/user/signup>

### 2: 앱 등록하기

* 매체 관리 메뉴에서 앱(AOS/iOS) 등록합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FA6a0u6ULWskEPtSfpnjc%2Fimage.png?alt=media&amp;token=e9acd07c-2651-453f-9a3c-4fdbc0dd1f1f" alt=""><figcaption><p>매체 등록 화면</p></figcaption></figure>

### 3: 슬롯 등록하기

* 앱 매체를 등록한 후 슬롯 버튼을 통해 각 광고 지면별 슬롯을 추가합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FQZjpdHIfbXFAb39xcau0%2Fimage.png?alt=media&amp;token=e127b39c-adb6-4c7a-9535-984148bf2c65" alt=""><figcaption><p>슬롯 추가 화면</p></figcaption></figure>

### 4: 지원 광고 규격

* 배너 광고

  320x50 / 320x100 / 320x480 / 300x250
* 전면 광고

  320x480 / 480x320
* 네이티브 광고
* 리워드 비디오 광고

### 5: 다음

* 발급받은 Media ID / Slot ID를 활용하여 이후 가이드에 적용합니다.


# 프로젝트 설정

### 1 : SDK 연동을 위한 준비

* Android Studio 환경
* Android 4.1 (API Version 16) 이상
* Android Support Library

### 2 : Gradle 연동

#### 1. 라이브러리 설정

**Android Studio (jitpack을 통한 설정)**

* AdPie SDK는 `jitpack`을 통해 AAR 파일을 사용할 수 있으며, `build.gradle` 파일에 아래의 내용을 추가합니다.
* Support Library 를 사용하기 위해 `Google Maven Repository` 를 마찬가지로 추가합니다.

```
repositories {
    google()
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'com.github.adxcorp:adpie-android-sdk:1.17.0'
}
```

### 3 : Java 호환성

* Java 8 언어 기능을 지원을 위해 `build.gradle` 파일에 android 섹션에서 compileOptions 을 추가합니다.

```
android {
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    // For Kotlin projects
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
```


# 광고 연동

{% content-ref url="/pages/CKftpsSmvHLwxGvlXN00" %}
[배너 광고](https://platform-business.gitbook.io/adpie/android/integration/banner)
{% endcontent-ref %}

{% content-ref url="/pages/ZbziQwj4OCN5B2h8twUB" %}
[전면 광고](https://platform-business.gitbook.io/adpie/android/integration/interstitial)
{% endcontent-ref %}

{% content-ref url="/pages/dqLPdrZxWMffs9tpLIG4" %}
[네이티브 광고](https://platform-business.gitbook.io/adpie/android/integration/native)
{% endcontent-ref %}

{% content-ref url="/pages/lMpJf147x2SfFTX99GNW" %}
[리워드 비디오 광고](https://platform-business.gitbook.io/adpie/android/integration/rewardedad)
{% endcontent-ref %}


# 배너 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/android/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : 레이아웃 XML에 슬롯 지정

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 XML 또는 자바코드에서 필수로 설정해주어야 합니다.
* 광고뷰가 사이트에서 설정한 슬롯 사이즈보다 작은 경우 요청하지 않거나 표출하지 않습니다.

```xml
<com.gomfactory.adpie.sdk.AdView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ad_view"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    slotID="AdPie-Slot-ID" >
</com.gomfactory.adpie.sdk.AdView>
```

### 3 : 광고 요청과 표출

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 호출해야 합니다.
* Step 2에서 xml 광고뷰에 Slot ID 를 넣지 않았다면, `setSlotId("AdPie-Slot-ID")` 메소드를 통해 입력합니다.
* `setScaleUp(true)`를 통해 정해진 영역내에서 비율을 유지하여 최대 2배까지 확대 가능합니다. (세로모드 기준으로 가로모드 제외)
* 띠배너에 `setScaleUp(true)`을 적용하면 스마트폰 기준으로 너비가 꽉채워지며 320x50 광고의 경우 높이는 50dp \~ 100dp가 됩니다.
* 광고 컨텐츠에 맞게 광고뷰 좌우여백의 색상을 채우고자 한다면 `setAutoBgColor(true)`메소드를 호출합니다. (스케일업 배너 제외)

```java
private AdView adView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // SDK 초기화로 앱실행 1회만 호출해야 합니다. (Main Activity 에 필수로 입력합니다.)
    AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");

    ...

    // 광고 연동을 위한 슬롯 ID를 필수로 입력합니다.
    adView = (AdView) findViewById(R.id.ad_view);
    // adView.setSlotId("AdPie-Slot-ID");
    
    /** Optional
    // 스케일배너 적용 : 기본값은 false
    adView.setScaleUp(true);
    // 자동 배경색상 적용 : 기본값은 false (스케일배너 제외)
    adView.setAutoBgColor(true);
    **/

    adView.load();
}

@Override
protected void onDestroy() {
    if (adView != null) {
        adView.destroy();
        adView = null;
    }

    super.onDestroy();
}
```

### 4 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* [에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```java
adView.setAdListener(new com.gomfactory.adpie.sdk.AdView.AdListener() {
        @Override
        public void onAdLoaded() {
                // 광고 표출 성공 후 이벤트 발생
        }
        
        @Override
        public void onAdFailedToLoad(int errorCode) {
                // 광고 요청 또는 표출 실패 후 이벤트 발생
                // error message -> AdPieError.getMessage(errorCode)
        }
        
        @Override
        public void onAdClicked() {
                // 광고 클릭 후 이벤트 발생
        }
}
```


# 전면 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/android/project-settings)을 통해 광고 연동을 위한 준비를 합니다.
* [사이트](http://my.adpies.com) 에서 매체를 등록하여 Media ID와 Slot ID 를 발급받습니다.
* 전면 광고의 경우 이미지와 비디오가 있으며, 대시보드에서 광고유형을 `Image` 또는 `Video` 를 필수적으로 하나 선택해야 합니다.
* 전면 비디오 광고는 보통 높은 단가를 형성하여 이미지 광고 보다 우선적으로 노출하는 것을 권장합니다.

```diff
- (주의사항) 전면 비디오 광고를 노출하기 위해서는 SDK 1.12.0 버전 이상을 연동해야 합니다.
```

### 2 : 광고 요청과 표출

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 호출합니다.
* 사이트에서 발급받은 Slot ID를 입력하여 InterstitialAd 객체를 생성합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있습니다.
* 광고 요청시 load() 메소드를 호출하고, 표출 시 show()를 호출합니다.
* 광고 컨텐츠가 로드되지 않을 가능성이 있기에 isLoaded()를 통해 확인 후 show() 메소드를 호출합니다.

```java
private InterstitialAd interstitialAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // SDK 초기화로 앱실행 1회만 호출한다. (Main Activity 에 필수로 입력한다.)
    AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");

    ...

    // 광고 연동을 위한 슬롯 ID를 필수로 입력한다.
    interstitialAd = new InterstitialAd(this, "AdPie-Slot-ID");
    interstitialAd.load();
}
```

### 3 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* [에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

#### 1) 공통 (전면 이미지, 전면 비디오)

```java
 interstitialAd.setAdListener(
     new com.gomfactory.adpie.sdk.InterstitialAd.InterstitialAdListener() {
         @Override
         public void onAdLoaded() {
             // 광고 로딩 완료 후 이벤트 발생

             // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가
             if (interstitialAd.isLoaded()) {
                 // 광고 표출
                 interstitialAd.show();
             }
         }

         @Override
         public void onAdFailedToLoad(int errorCode) {
            // 광고 요청 실패 후 이벤트 발생
            // error message -> AdPieError.getMessage(errorCode)
         }

         @Override
         public void onAdShown() {
            // 광고 표출 후 이벤트 발생
         }

         @Override
         public void onAdClicked() {
            // 광고 클릭 후 이벤트 발생
         }

         @Override
         public void onAdDismissed() {
            // 광고 닫기 후 이벤트 발생
         }
         
         @Override
         public void onAdFailedToShow() {
            // 광고 표출 실패 후 이벤트 발생
         }
     }
 );
```

#### 2) 전면 비디오 전용 리스너 (VideoPlaybackListener)

```java
interstitialAd.setVideoAdPlaybackListener(
    new VideoAdPlaybackListener() {
            @Override
            public void onVideoAdStarted() {
                // 비디오 재생 시작
            }

            @Override
            public void onVideoFinished(FinishState finishState) {
                // 비디오 재생 종료
                
                switch (finishState) {
                    case ERROR: // 동영상 광고 오류
                    case SKIPPED: // 동영상 광고 건너뜀
                    case COMPLETED: // 동영상 광고 시청완료
                        break;
                }
            }
});
```


# 네이티브 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/android/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : 이미지 모듈 설정

* SDK에서는 이미지 모듈로 [Glide](https://github.com/bumptech/glide)가 포함되어 있다면 사용하도록 되어있습니다.
* GIF 이미지 처리가 가능하고, 메모리 사용에 효율적인 Glide 사용을 권장합니다.
* 이미지를 직접 핸들링하고자 한다면 해당 Step은 건너뛰고, 페이지 하단의 `이미지 직접 핸들링`을 확인합니다.
* Glide 의 경우 v4.4 이상 지원하고 v4.4 미만의 버전은 지원을 중단하여 캐싱되지 않은 상태로 로딩합니다.
* `build.gradle` 파일에 아래와 같이 추가를 합니다.

```
dependencies {
    // Glide 사용시
    compile 'com.github.bumptech.glide:glide:4.+'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.+'
}
```

### 3 : 레이아웃 관련 설정

#### 1. 광고요소 선택

* 네이티브 광고의 요소 (**`① 아이콘`** **`② 제목`** **`③ 설명`** **`④ 메인`** `⑤ 액션버튼`) 중 사용할 요소를 미리 결정합니다.
* 단, `① 아이콘` `② 제목` `③ 설명` `④ 메인` 중 최소 하나는 필수적으로 들어가야 하며, 선택한 요소에 따라 광고 물량에 차이가 발생합니다.
* `⑤ 액션버튼` 이 없을 때보다 있을 때 CTR이 높게 나오기에 가능한 넣는 것을 추천합니다.
* `⑥ 옵트아웃` 은 자동으로 우측 상단에 붙이고 있기에 텍스트 영역과 겹치지 않도록 고려해야 합니다. (옵트아웃 이미지 크기 : 14dp, 상단 및 우측 여백 : 5dp)
* `⑥ 옵트아웃` 의 위치와 크기를 바꾸려면 XML과 NativeAdViewBinder 에 넣어주어야 하며 크기는 정사이즈로 만듭니다.

![네이티브 샘플](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_native_sample.png)

* 대시보드를 통해 슬롯을 생성하는 과정에서 슬롯유형에 네이티브(Native)를 선택하고, 네이티브 유형을 체크를 합니다.
* 네이티브 유형은 앞서 선택한 필수 요소 (`① 아이콘` `② 제목` `③ 설명` `④ 메인`)에 해당됩니다.

![네이티브 유형](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_native_type.png)

* 체크한 유형은 XML과 NativeAdViewBinder 에 필수로 들어가야 광고를 성공적으로 받아볼 수 있습니다.

#### 2. XML 정의

* 아래의 예시는 광고의 요소(아이콘, 제목, 설명, 메인)이 놓여질 형태를 나타낸 것으로, 광고를 보여줄 layout 파일을 생성하여 정의를 합니다.
* 네이티브 광고 템플릿 파일인 [res/layout/adpie\_native\_ad\_template.xml](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/res/layout/adpie_native_ad_template.xml)를 참고하여 원하는 형태로 레이아웃을 구성합니다.

```xml
<RelativeLayout ...>

    <!-- 옵트아웃 (Opt-out) -->
    <ImageView
            android:id="@+id/native_optout" ... />

    <!-- 아이콘 (Icon) -->
    <ImageView
            android:id="@+id/native_ad_icon" ... />

    <!-- 제목 (Title) -->
    <TextView
            android:id="@+id/native_ad_title" ... />

    <!-- 설명 (Description) -->
    <TextView
        android:id="@+id/native_ad_description" ... />

    <!-- 메인 이미지 (Main) -->
    <com.gomfactory.adpie.sdk.nativeads.MainAdView
        android:id="@+id/native_ad_main" ... />

    <!-- 액션버튼 (Call-To-Action) -->
    <Button
        android:id="@+id/native_ad_cta" ... />

</RelativeLayout>
```

#### 3. NativeAdViewBinder 생성

* NativeAdViewBinder 객체를 생성하고, xml에 정의한 Layout ID와 광고 요소별 id(icon, title, description, main)를 설정합니다.

```java
NativeAdViewBinder viewBinder = new NativeAdViewBinder.Builder(R.layout.adpie_native_ad) // Layout ID
    .setIconImageId(R.id.native_ad_icon) // Icon ID
    .setTitleId(R.id.native_ad_title) // Title ID
    .setDescriptionId(R.id.native_ad_description) // Description ID
    .setMainId(R.id.native_ad_main) // Main ID
    .setCallToActionId(R.id.native_ad_cta) // Call-To-Action ID
    .setOptOutId(R.id.native_optout) // Opt-out ID
    .build();
```

### 4 : 광고 요청과 표출

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 호출합니다.
* 사이트에서 발급받은 Slot ID와 앞서 생성한 NativeAdViewBinder 객체를 인자값으로 넣어 NativeAd 객체를 생성합니다.

```java
private NativeAd nativeAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // SDK 초기화로 앱실행 1회만 호출합니다. (Main Activity 에 필수로 입력)
        AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");
        
        ...
        
        NativeAdViewBinder viewBinder = new NativeAdViewBinder.Builder(R.layout.adpie_native_ad) // Layout ID
                .setIconImageId(R.id.native_ad_icon) // Icon ID
                .setTitleId(R.id.native_ad_title) // Title ID
                .setDescriptionId(R.id.native_ad_description) // Description ID
                .setMainId(R.id.native_ad_main) // Main ID
                .setCallToActionId(R.id.native_ad_cta) // Call-To-Action ID
                .setOptOutId(R.id.native_optout) // Opt-out I
                .build();
        
        // 광고 연동을 위한 슬롯 ID를 필수로 입력
        nativeAd = new NativeAd(this, "AdPie-Slot-ID", viewBinder);
        // 광고 호출
        nativeAd.loadAd();
}
```

### 5 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* 광고 성공 또는 실패 이벤트를 전혀 못받는 경우 페이지 하단의 `이미지 직접 핸들링`을 확인하여 적용합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```java
nativeAd.setAdListener(new com.gomfactory.adpie.sdk.NativeAd.AdListener() {
        @Override
        public void onAdLoaded(final NativeAdView nativeAdView) {
            // 광고 로딩 완료 후 이벤트 발생
            // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.

            ViewGroup adContainer = (ViewGroup)findViewById(R.id.ad_container);
            adContainer.removeAllViews();
            adContainer.addView(nativeAdView);
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            // 광고 요청 또는 표출 실패 후 이벤트 발생
            // error message -> AdPieError.getMessage(errorCode)
        }

        @Override
        public void onAdShown() {
            // 광고 표출 후 이벤트 발생
        }

        @Override
        public void onAdClicked() {
            // 광고 클릭 후 이벤트 발생
        }
    });
```

### 6 : 이미지 직접 핸들링

* SDK를 통해 이미지 다운로드를 바로 진행하는 것은 기본 설정입니다.
* 만약 직접 핸들링하고자 한다면, Step 4에서 NativeAd 객체 생성 후 setSkipDownload(true) 를 호출합니다.
* setSkipDownload(true) 호출시 이미지 모듈의 우선순위는 무시되고, 이미지 다운로드를 건너뜁니다.
* 광고 리스너를 통해 onAdLoaded() 받으면, 이미지를 직접 호출 및 설정해야 합니다.

```java
// 광고 연동을 위한 슬롯 ID를 필수로 입력합니다.
nativeAd = new NativeAd(this, "AdPie-Slot-ID", viewBinder);

// SDK에서 리소스 다운로드를 하지 않기 위한 설정
nativeAd.setSkipDownload(true);
// 광고 리스너 사용
nativeAd.setAdListener(new com.gomfactory.adpie.sdk.NativeAd.AdListener() {
        @Override
        public void onAdLoaded(final NativeAdView nativeAdView) {

            // 이미지 다운로드 및 설정이 필요
            NativeAdData nativeAdData = nativeAdView.getNativeAdData();
            String iconImageUrl = nativeAdData.getIconImageUrl();
            ImageView iconImageView = nativeAdView.getIconImageView();
            String mainImageUrl = nativeAdData.getMainImageUrl();
            ImageView mainImageView = nativeAdView.getMainImageView();
        }
    });
// 광고 호출
nativeAd.loadAd();
```


# 리워드 비디오 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/android/project-settings)을 통해 광고 연동을 위한 준비를 합니다.
* [사이트](http://my.adpies.com) 에서 매체를 등록하여 Media ID와 Slot ID 를 발급받습니다.

### 2 : 광고 요청과 표출

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 호출합니다.
* 사이트에서 발급받은 Slot ID를 입력하여 RewardedVideoAd 객체를 생성합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있습니다.
* 광고 요청시 load() 메소드를 호출하고, 표출 시 show()를 호출합니다.
* 광고 컨텐츠가 로드되지 않을 가능성이 있기에 isLoaded()를 통해 확인 후 show() 메소드를 호출합니다.

```java
private RewardedAd rewardedAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // SDK 초기화로 앱실행 1회만 호출합니다. (Main Activity 에 필수로 입력)
    AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");

    ...

    // 광고 연동을 위한 슬롯 ID를 필수로 입력합니다.
    rewardedAd = new RewardedAd(this, "AdPie-Slot-ID");
    rewardedAd.load();
}
```

### 3 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* 광고 수신 후 바로 노출하지 않는 경우에는 onAdDismissed 콜백에서 광고를 재요청하는 로직을 추천합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```java
rewardedAd.setAdListener(new RewardedAd.RewardedAdListener() {
    @Override
    public void onAdLoaded() {
        // 광고 로딩 완료 후 이벤트 발생

        // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
        if (rewardedAd.isLoaded()) {
            // 광고 표출
            rewardedAd.show();
        }
    }

    @Override
    public void onAdFailedToLoad(int errorCode) {
        // 광고 요청 실패 후 이벤트 발생
    }

    @Override
    public void onAdShown() {
        // 광고 노출 후 이벤트 발생
    }

    @Override
    public void onAdClicked() {
        // 광고 클릭 후 이벤트 발생
    }

    @Override
    public void onAdDismissed() {
        // 광고 닫기 후 이벤트 발생
    }

    @Override
    public void onAdRewarded() {
        // 보상 발생 후 이벤트 발생
    }

    @Override
    public void onAdFailedToShow() {
        // 광고 표출 실패 후 이벤트 발생
    }
});
```


# 리워드 비디오 광고 (1.15.1 이하)

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/android/project-settings)을 통해 광고 연동을 위한 준비를 합니다.
* [사이트](http://my.adpies.com) 에서 매체를 등록하여 Media ID와 Slot ID 를 발급받습니다.

### 2 : 광고 요청과 표출

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 호출합니다.
* 사이트에서 발급받은 Slot ID를 입력하여 RewardedVideoAd 객체를 생성합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있습니다.
* 광고 요청시 load() 메소드를 호출하고, 표출 시 show()를 호출합니다.
* 광고 컨텐츠가 로드되지 않을 가능성이 있기에 isLoaded()를 통해 확인 후 show() 메소드를 호출합니다.

```java
private RewardedVideoAd rewardedVideoAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // SDK 초기화로 앱실행 1회만 호출합니다. (Main Activity 에 필수로 입력)
    AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");

    ...

    // 광고 연동을 위한 슬롯 ID를 필수로 입력합니다.
    rewardedVideoAd = new RewardedVideoAd(this, "AdPie-Slot-ID");
    rewardedVideoAd.load();
}
```

### 3 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* 광고 수신 후 바로 노출하지 않는 경우에는 onRewardedVideoFinished 에서 광고를 재요청하는 로직을 추천합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```java
rewardedVideoAd.setAdListener(new RewardedVideoAd.RewardedVideoAdListener() {
	
    @Override
    public void onRewardedVideoLoaded() {
	    // 광고 로딩 완료 후 이벤트 발생

        // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
        if (rewardedVideoAd.isLoaded()) {
            // 광고 표출
            rewardedVideoAd.show();
        }
    }

    @Override
    public void onRewardedVideoFailedToLoad(int errorCode) {
	    // 광고 요청 실패 후 이벤트 발생 
    }

    @Override
    public void onRewardedVideoClicked() {
        // 광고 클릭 후 이벤트 발생
    }

    @Override
    public void onRewardedVideoStarted() {
        // 동영상 광고 시작 알림
    }

    @Override
    public void onRewardedVideoFinished(FinishState finishState) {
        // 동영상 광고 종료 알림

        switch (finishState) {
            case ERROR: // 동영상 광고 오류
            case SKIPPED: // 동영상 광고 건너뜀
            case COMPLETED: // 동영상 광고 시청완료
                break;
        }
    }
});
```


# 미디에이션

{% content-ref url="/pages/yZznB2GRxE3drFvjPnRv" %}
[구글 애드몹](https://platform-business.gitbook.io/adpie/android/mediation/admob)
{% endcontent-ref %}

{% content-ref url="/pages/8Rzd35gBllH1hhcHgBrz" %}
[구글 애드 매니저](https://platform-business.gitbook.io/adpie/android/mediation/admanager)
{% endcontent-ref %}

{% content-ref url="/pages/RK909WKyp8L9Phs4GzNo" %}
[앱러빈](https://platform-business.gitbook.io/adpie/android/mediation/applovin)
{% endcontent-ref %}


# 구글 애드몹

구글 애드몹의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : Custom Event 클래스 추가

* [AdPieBannerLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieBannerLoader.java) : 애드파이 호출을 위한 띠배너용 클래스
* [AdPieInterstitialLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieInterstitialLoader.java) : 애드파이 호출을 위한 전면배너용 클래스
* [AdPieRewardedAdLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieRewardedAdLoader.java) : 애드파이 호출을 위한 리워드 비디오용 클래스
* [AdPieMediationAdapter.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieMediationAdapter.java) : 구글 미디에이션을 위한 CustomEvent 클래스
* 위의 4개의 클래스는 `com.google.ads.mediation.adpie` 패키지에 위치하고 있으며, 개발중인 앱 프로젝트에 복사를 진행합니다.

### 2 : 미디에이션 등록(Custom Event)

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [Custom Event](https://support.google.com/admob/answer/3083407?ctx=tltp\&hl=ko) 를 확인합니다.
* 1\) [애드몹](https://apps.admob.com) 사이트 통해 로그인을 합니다.
* 2\) 사이드바에서 **미디에이션**을 클릭합니다.
* 3\) 미디에이션 그룹의 이름을 클릭합니다.
* 4\) 폭포식 구조 광고 소스 표의 **맞춤 이벤트** 추가를 클릭합니다.
* 5\) 이벤트를 설명하는 라벨을 입력합니다.
* 6\) 이 맞춤 이벤트에 사용할 수동 eCPM을 입력합니다.
* **7) 계속**을 클릭합니다.
* 8\) 각 광고 단위의 **클래스 이름(필수)** 및 **매개변수(선택사항)** 를 입력합니다.

> Class Name 정보에는 패키지명을 포함하여 `com.google.ads.mediation.adpie.AdPieMediationAdapter` 와 같이 클래스 명을 입력합니다.

> Parameter(선택사항) 정보에는 AdPie에서 발급받은 **Media ID**와 **Slot ID**를 `{"app_id":"Insert_Media_ID", "slot_id":"Insert_Slot_ID"}` 형식으로 입력합니다.

![Custom Event](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_admob_customevent2.png)

* 9\) **완료** 버튼을 클릭합니다.
* **10) 저장** 버튼을 클릭합니다.


# 구글 애드 매니저

구글 애드 매니저의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : Custom Event 클래스 추가

* [AdPieBannerLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieBannerLoader.java) : 애드파이 호출을 위한 띠배너용 클래스
* [AdPieInterstitialLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieInterstitialLoader.java) : 애드파이 호출을 위한 전면배너용 클래스
* [AdPieRewardedAdLoader.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieRewardedAdLoader.java) : 애드파이 호출을 위한 리워드 비디오용 클래스
* [AdPieMediationAdapter.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/google/ads/mediation/adpie/AdPieMediationAdapter.java) : 구글 미디에이션을 위한 CustomEvent 클래스
* 위의 4개의 클래스는 `com.google.ads.mediation.adpie` 패키지에 위치하고 있으며, 개발중인 앱 프로젝트에 복사를 진행합니다.

### 2 : 미디에이션 등록

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [미디에이션](https://support.google.com/admanager/answer/6272813?hl=ko\&sjid=17829723247869263806-AP) 를 확인합니다.
* 1\) [애드 매니저](https://admanager.google.com) 사이트 통해 로그인을 합니다.
* 2\) 수익 파트너 등록이 되어 있지 않으면 아래와 같이 등록합니다.
* ```
  (1) 관리 > 업체을 클릭합니다.
  (2) 새 회사를 클릭합니다.
  (3) 광고 네트워크를 선택합니다.
  (4) 이름에 'AdPie'로 입력합니다.
  (5) 광고 네트워크에서 'MoPub'을 선택하고 미디에이션을 활성화합니다.
  (6) 저장을 누릅니다.
  ```

![Custom Event](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_admanager_customevent.png)

* 3\) 수익 그룹이 등록되어 있지 않으면 아래와 같이 등록합니다.
* ```
  (1) 게재 > 수익 그룹을 클릭합니다.
  (2) 새 수익 그룹을 클릭합니다.
  (3) 보고를 위해 알아보기 쉬운 고유한 수익 그룹 이름을 입력합니다.
  (4) 수익 그룹으로 타겟팅하려는 광고 형식과 인벤토리 유형을 선택합니다.
  (5) 저장을 누릅니다.
  ```
* 4\) 수익 그룹에서 AdPie를 수익파트너로 추가합니다.
* ```
  (1) 게재 > 수익 그룹을 클릭합니다.
  (2) 수정할 수익 그룹의 이름을 클릭합니다.
  (3) 수익 파트너 추가를 클릭합니다.
  (4) 수익 파트너 드롭다운에서 앞에서 등록한 'AdPie' 수익 파트너를 선택합니다.
  (5) 통합 유형을 '맞춤 이벤트'로 기본 설정 확인합니다.
  (6) 타겟팅하려는 플랫폼(Android)을 선택합니다.
  (7) 상태 ('운영중' 또는 '비활성화')를 선택합니다.
  (8) 기본 CPM을 입력합니다.
  (9) 추가 수익 파트너 세부 정보를 입력합니다. (자세한 내용은 아래 참고합니다.)
  (10) 저장을 누릅니다.
  ```

> Label은 구분하기 쉬운 값을 입력합니다.

> Class Name 정보에는 패키지명을 포함하여 `com.google.ads.mediation.adpie.AdPieMediationAdapter` 와 같이 클래스 명을 입력합니다.

> Parameter(선택사항) 정보에는 AdPie에서 발급받은 **Media ID**와 **Slot ID**를 `{"app_id":"Insert_Media_ID", "slot_id":"Insert_Slot_ID"}` 형식으로 입력합니다.

![Custom Event](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_admanager_customevent2.png)


# 앱러빈

앱러빈의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : Custom Event 클래스 추가

* [AdPieMediationAdapter.java](https://github.com/gomfactory/AdPie-Android-SDK/blob/master/AdPieSample/app/src/main/java/com/applovin/mediation/adapters/AdPieMediationAdapter.java) : 앱러빈 미디에이션을 위한 CustomEvent 클래스
* 위의 클래스는 `com.applovin.mediation.adapters` 패키지에 위치하고 있으며, 개발중인 앱 프로젝트에 복사를 진행합니다.

### 2 : 미디에이션 등록(Custom Event)

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [Custom SDK Network Integration Guide](https://dash.applovin.com/documentation/mediation/android/mediation-setup/custom-sdk) 를 확인합니다.
* 1\) [앱러빈](https://www.applovin.com) 사이트 통해 로그인을 합니다.
* 2\) 사이드바에서 [MAX > Mediation > Manage > Networks](https://dash.applovin.com/o/mediation/networks/) 를 선택합니다.
* 3\) 페이지 하단에 있는 **Click here to add a Custom Network**를 클릭합니다.
* 4\) Network Type은 **SDK**를 선택하고 Custom Network 이름을 입력합니다.
* 5\) Android / Fire OS Adapter Class Name에 `com.applovin.mediation.adapters.AdPieMediationAdapter` 와 같이 패키지명을 포함하여 클래스명을 입력합니다.

![Custom Network1](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_applovin_customevent1.png)

* 6\) 저장 (Save)를 클릭합니다.
* 7\) [MAX > Mediation > Manage > Ad Units](https://dash.applovin.com/o/mediation/ad_units/) 에서 AdPie를 추가할 Ad Unit을 선택합니다.
* **8) App ID (optional)** 에 AdPie에서 발급받은 `Media ID` 를 **Placement ID** 에 `Slot ID`를 입력합니다.

![Custom Network2](https://github.com/gomfactory/AdPie-Android-SDK/wiki/image/android_sdk_applovin_customevent2.png)

* 9\) 저장 (Save)를 클릭합니다.


# 공통

{% content-ref url="/pages/hmiKLbhBlpBBrEZ2ERDz" %}
[에러코드](https://platform-business.gitbook.io/adpie/android/common/errorcode)
{% endcontent-ref %}

{% content-ref url="/pages/WzaxNLeaUwGbrWjofGwj" %}
[디버깅](https://platform-business.gitbook.io/adpie/android/common/debug)
{% endcontent-ref %}

{% content-ref url="/pages/NX1eAUIFykBbXuITgjdJ" %}
[변경내역](https://platform-business.gitbook.io/adpie/android/changelog)
{% endcontent-ref %}


# 에러코드

* SDK를 통한 광고 실패에 대한 코드와 메시지를 아래와 같이 정의합니다.

|  code | message                                           | description                                                       |
| :---: | ------------------------------------------------- | ----------------------------------------------------------------- |
| `100` | No fill.                                          | 광고 없음                                                             |
| `101` | Invalid ad request.                               | 잘못된 요청 파라미터 (Media ID, Slot ID, Package Name 확인)                  |
| `102` | A network error occurred.                         | 네트워크 오류 (서버통신 오류, 지속시 문의필요)                                       |
| `103` | No internet connection detected.                  | 연결된 인터넷 정보 없음 (인터넷 연결상태 확인)                                       |
| `104` | An internal error occurred.                       | 내부 오류 (발생시 문의필요)                                                  |
| `105` | AdPie SDK must be initialized before ads loading. | SDK 초기화 미완료 (연동 실패)                                               |
| `106` | Previous ad request is being processed.           | 중복 요청 (기존 요청이 끝나기전에 재요청)                                          |
| `107` | An error occurred while loading content.          | 컨텐츠 로딩 오류 (웹뷰의 컨텐츠 로딩실패)                                          |
| `108` | A server data error occurred.                     | 서버 데이터 오류 (데이터 파싱, 지속시 문의필요)                                      |
| `109` | Invalid ad layout.                                | 레이아웃 설정 오류 (배너의 경우 백그라운드 상태이거나 잘못된 슬롯 사이즈, 네이티브의 경우 필수 요소가 빠진 상태) |
| `110` | Ad request was blocked with minimum time limit.   | 광고 요청의 시간 제한 (기존 요청의 시간 비교 후 서버 전송 없음)                            |


# 디버깅

* 연동 과정에서 디버깅을 필요하다면, 아래와 같이 코드를 적용하여 LogCat에서 'AdPieSDK'의 Tag를 검색하여 확인합니다.

```java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 디버깅 적용
        AdPieLog.setLogEnable(true);
        AdPieLog.setLogLevel(Log.DEBUG);

        // SDK 초기화 (Main Activity에 필수로 입력)
        AdPieSDK.getInstance().initialize(getApplicationContext(), "AdPie-Media-ID");

    }
```


# 샘플 애플리케이션

{% embed url="<https://github.com/gomfactory/AdPie-Android-SDK/tree/master/AdPieSample>" %}


# 변경내역

### 1.17.0 (2026년 10월 20일)

* 전면, 리워드 비디오 광고 UI 개편

### 1.16.8 (2026년 09월 28일)

* 네이티브 광고의 onPaidEvent 관련 추가

### 1.16.7 (2026년 09월 17일)

* 네이티브 광고 노출률(응답속도) 개선

### 1.16.6 (2026년 08월 24일)

* 전면 풀스크린 웹뷰 광고 지원

### 1.16.5 (2026년 06월 05일)

* 광고 로드 콜백에 AdInfo 전달 추가 (기존 콜백과 호환)

### 1.16.4 (2026년 03월 05일)

* 배너 광고의 가시성(Viewability) 측정 기능 추가

### 1.16.3 (2026년 02월 03일)

* 네이티브 광고뷰(NativeAdView)의 메모리 사용 개선

### 1.16.2 (2026년 01월 06일)

* 비디오 캐시 기능 추가 (비디오 재생 속도 개선)
* 프리롤 광고, 다이얼로그 광고 코드 제거

### 1.16.1 (2025년 11월 26일)

* 가로형 비디오 광고에서 일부 요소와 네비게이션바 겹침 문제 해결

### 1.16.0 (2025년 11월 18일)

* 신규 보상형 광고 클래스 (RewardedAd) 추가
* 기존 보상형 광고 클래스 (RewardedVideoAd) Deprecated 처리
* 비디오 광고에서 옵트아웃과 네비게이션바 겹침 문제 해결
* 전면 광고의 onAdFailedToShow() 콜백 메소드 추가

### 1.15.1 (2025년 11월 05일)

* 네트워크 라이브러리 사용 지원
* 안전성 향상

### 1.15.0 (2025년 09월 01일)

* OS 16 대응
* 최소 SDK 버전 상향 조정 (API 15->16)

### 1.14.6 (2025년 08월 19일)

* 연동 라이브러리 최적화

### 1.14.5 (2025년 07월 17일)

* 전면 비디오 광고의 VideoPlaybackListener 추가

### 1.14.4 (2025년 06월 17일)

* 광고 로딩바 수정
* 내부 에러코드 수정

### 1.14.3 (2025년 05월 12일)

* 광고 액티비티에 테마 적용
* 비디오 광고 기능 개선

### 1.14.2 (2025년 02월 26일)

* 비디오 광고 기능 개선

### 1.14.1 (2024년 12월 17일)

* 안정성 향상

### 1.14.0 (2024년 11월 06일)

* 배너 광고 개선

### 1.13.7 (2024년 09월 23일)

* 비디오 광고 안정화
* 뉴스 광고 개선

### 1.13.6 (2024년 06월 19일)

* 비디오 광고 클릭 후 재생 불가에 대한 수정

### 1.13.5 (2024년 06월 05일)

* 쿠팡 광고 최적화

### 1.13.4 (2024년 03월 28일)

* 전면과 리워드 광고의 닫기 버튼 기능 개선

### 1.13.3 (2024년 03월 07일)

* 비디오 광고 resume 개선
* 웹뷰 광고의 alert 방지 적용

### 1.13.2 (2024년 01월 11일)

* 사운드 재생 관련 대응

### 1.13.1 (2023년 08월 03일)

* 네이티브 광고 안정화 작업

### 1.13.0 (2023년 07월 27일)

* 타겟 SDK 변경 (API 33, Android 13)
* 최소 SDK 버전 상향 조정 (API 14->15)
* 비디오 광고 SeekBar 및 CTA 제거

### 1.12.3 (2023년 07월 04일)

* 전면 비디오 광고의 SeekBar 제거

### 1.12.2 (2023년 04월 13일)

* 비디오 광고의 가로/세로 모드 구분 처리
* 전면 이미지 광고의 가로 모드 적용 (480x320)

### 1.12.1 (2023년 03월 24일)

* 전면 광고와 리워드 비디오 광고의 닫기 버튼 및 프로그레스바 변경

### 1.12.0 (2023년 03월 10일)

* 전면 비디오 광고 추가
* 전면 이미지 광고 클릭시 광고 화면 유지하도록 수정

### 1.11.0 (2023년 03월 06일)

* 광고 트래픽을 HTTPS 통해서만 처리되도록 수정
* 배너 광고 관련 개선

### 1.10.1 (2023년 02월 02일)

* LocalBroadcastManager 라이브러리 dependency에 추가
* 타겟 SDK 변경 (API 31, Android 12)

### 1.10.0 (2023년 01월 20일)

* 광고 중복요청 관련 개선 (기존 요청에 대해 처리완료까지 이후 요청은 모두 실패 처리)

### 1.9.9 (2022년 12월 29일)

* 리워드 비디오 광고의 SSV(Server-Side-Verification) 기능 추가

### 1.9.8 (2022년 11월 02일)

* 리워드 비디오 광고 관련 개선 (세로형 비디오 광고 대응)

### 1.9.7 (2022년 09월 30일)

* 프리롤 광고 관련 개선

### 1.9.6 (2022년 09월 16일)

* 리워드 비디오 광고 관련 개선

### 1.9.5 (2022년 05월 04일)

* 전면 이미지 광고에서 네비게이션 바 표출되도록 수정

### 1.9.4 (2022년 02월 14일)

* 리워드 비디오 광고 관련 UI 수정

### 1.9.3 (2021년 12월 27일)

* 안드로이드 12 관련 대응

### 1.9.2 (2021년 09월 06일)

* 웹뷰 랜딩 관련 보완

### 1.9.1 (2021년 06월 09일)

* 일부 광고 캠페인의 랜딩 페이지 변경 (웹뷰 적용)

### 1.9.0 (2021년 06월 02일)

* jCenter 종료에 따른 jitpack 으로 저장소 이전
* 타겟 SDK 변경 (API 30, Android 11)
* 안드로이드 11 관련 대응

### 1.8.4 (2020년 11월 10일)

* 전면광고의 종료 딜레이 관련 수정

### 1.8.3 (2020년 10월 15일)

* 1.8.2 버전 보완 (클릭 수집)

### 1.8.2 (2020년 09월 23일)

* 배너 클릭 관련 일부 기능 추가

### 1.8.1 (2020년 09월 08일)

* 타겟 SDK 변경 (API 29, Android 10)
* AndroidX 마이그레이션

### 1.8.0 (2020년 06월 29일)

* 리워드 비디오 광고 적용
* 비디오 광고 리스너 관련 변경

### 1.7.7 (2020년 02월 19일)

* 광고 클릭에 대한 브라우저 우선순위 변경 가능하도록 적용

### 1.7.6 (2020년 02월 19일)

* 광고 클릭에 대한 삼성 브라우저 우선순위 적용

### 1.7.5 (2020년 01월 06일)

* 배너 광고 관련 성능 향상
* 배너의 백그라운드 색상 적용 (기존 배너에서 setAutoBgColor 메소드 호출)

### 1.7.4 (2020년 01월 02일)

* 배너 광고 노출 관련 개선
* 네이티브 광고 노출/클릭 집계의 허용치 수정

### 1.7.3 (2019년 11월 13일)

* 네이티브 광고 옵트아웃 조정
* 네이티브 특정 매체의 CTA 관련 변경
* 배너 백그라운드 관련 수정

### 1.7.2 (2019년 9월 27일)

* 웹뷰의 크롬 77 버전 관련 이슈 처리

### 1.7.1 (2019년 9월 26일)

* 배너 관련 성능 향상
* 배너의 백그라운드 색상 적용

### 1.7.0 (2019년 9월 20일)

* 배너 관련 성능 향상

### 1.6.8 (2019년 9월 6일)

* 일부 매체의 NullpointerException 발생 관련 수정

### 1.6.7 (2019년 8월 9일)

* 타겟팅 항목 변경

### 1.6.6 (2019년 7월 19일)

* 전면배너의 종료버튼 개선 (대시보드에서 노출시간 변경 가능)

### 1.6.5 (2019년 7월 9일)

* 스케일 배너 관련 개선
* 타겟팅 관련 변경

### 1.6.4 (2019년 7월 2일)

* 잠금화면 관련 기능 개선

### 1.6.3 (2019년 6월 17일)

* 옵트아웃(Opt-out) 이미지 축소
* 안정성 향상

### 1.6.2 (2019년 5월 21일)

* 타겟 SDK 변경 (API 28, Pie)
* 안드로이드 Pie (9) 관련 대응 (Https)
* 서비스 향상

### 1.6.1 (2019년 4월 5일)

* Gradle 오류로 인해 재배포

### 1.6.0 (2019년 4월 5일)

* 구글 개인정보보호 정책 관련 패치

### 1.5.8 (2019년 2월 28일)

* 배너의 광고 재요청 관련 개선

### 1.5.7 (2019년 2월 19일)

* 전면배너의 광고 리스너 중 onAdDismissed 관련 변경 (호출 시간 단축)

### 1.5.6 (2019년 1월 8일)

* TLS 1.1, TLS 1.2 관련 활성화 (Android 4.1 \~ 4.4.4)

### 1.5.5 (2019년 1월 3일)

* RecyclerView 에 배너 사용시 광고영역 확대 가능하도록 변경
* 전면배너 테마 제거 (Manifest 설정)

### 1.5.4 (2018년 9월 3일)

* 광고 클릭의 크롬 브라우저 우선 선택 적용

### 1.5.3 (2018년 6월 19일)

* 킷캣 관련 오류 수정

### 1.5.1 (2018년 4월 6일)

* 네이티브 광고 관련 Picasso 최신 버전 지원    (Picasso V2.5 이하 버전 지원 중단)
* 네이티브 비디오 광고 관련 수정
* 버그 수정

### 1.5.0 (2018년 3월 29일)

* 네이티브 비디오 광고 적용

### 1.4.10 (2018년 2월 6일)

* 다이얼로그 광고 관련 수정  (세로모드의 2/3 크기로 고정, 가로모드에서 메인이미지 노출)

### 1.4.9 (2017년 12월 21일)

* 전면배너의 광고영역 확대
* 전면배너 비디오 광고의 음소거 적용

### 1.4.8 (2017년 12월 14일)

* 네이티브 광고 관련 수정  (리스트뷰에 동일한 광고를 여러개 노출 가능)

### 1.4.7 (2017년 11월 15일)

* 다이얼로그 광고 스타일의 광고영역 패딩 추가

### 1.4.6 (2017년 11월 14일)

* 다이얼로그 광고 레이아웃 관련 수정 (ICS)

### 1.4.5 (2017년 11월 6일)

* 네이티브 광고 관련 Glide V4 지원  (Glide V3 지원 중단)

### 1.4.4 (2017년 11월 2일)

* 스케일 배너 관련 수정

### 1.4.3 (2017년 10월 13일)

* 다이얼로그 광고 관련 수정 (광고 캐싱)
* DialogAd (사용중지 예정)
* DialogAdV1 (배너형), DialogAdV2 (네이티브형) 추가

### 1.4.2 (2017년 9월 21일)

* 다이얼로그 광고 관련 수정

### 1.4.1 (2017년 9월 20일)

* ICS 관련 보완

### 1.4.0 (2017년 9월 19일)

* 네이티브 광고의 옵트아웃(OPT-OUT) 적용
* 타겟 SDK 변경 (API 26, Oreo)
* 최소 SDK 버전 상향 조정 (API 9->14, Gingerbread->ICS)
* ICS 관련 오류 수정

### 1.3.1 (2017년 8월 31일)

* 다이얼로그 광고 관련 업데이트
* 버튼 클릭시 자동으로 다이얼로그 사라지도록 처리

### 1.3.0 (2017년 8월 29일)

* 다이얼로그 광고 추가

### 1.2.2 (2017년 7월 26일)

* 태블릿 관련 스케일 배너 수정

### 1.2.1 (2017년 7월 25일)

* 스케일 배너 추가 (기존 배너에서 setScaleUp 메소드 호출)

### 1.2.0 (2017년 5월 8일)

* 비디오 광고 추가
* 프리롤 비디오 광고, 풀스크린 비디오 광고 (AndroidManifest.xml에서 액티비티 추가 필요)

### 1.1.8 (2017년 3월 3일)

* 하이브리드 앱 관련 수정
* AdPieWebViewJsBridge 클래스 추가 (하이브리드 앱에서 필수 호출)

### 1.1.7 (2017년 2월 9일)

* 광고 재요청 관련 수정

### 1.1.6 (2017년 2월 7일)

* 서비스 앱 관련 수정
* 광고 요청의 제한시간 적용
* 에러코드 \[110] 추가 (광고 요청 제한시간)

### 1.1.5 (2017년 1월 12일)

* 하이브리드 앱 관련 수정

### 1.1.4 (2016년 12월 26일)

* 하이브리드 앱 관련 수정 (setDisplayAdInWebview 메소드 추가)

### 1.1.3 (2016년 12월 20일)

* 하이브리드 앱 관련 수정

### 1.1.2 (2016년 11월 21일)

* 내부 데이터 저장 관련 개선

### 1.1.1 (2016년 8월 31일)

* SDK 초기화 관련 NullpointerException 보고에 대한 처리

### 1.1.0 (2016년 8월 24일)

* 네이티브 광고 추가

### 1.0.10 (2016년 7월 25일)

* LG 하위기종의 배너 초기화 오류 수정
* 버그 수정

### 1.0.9 (2016년 6월 28일)

* 네트워크 통신 관련 코드 수정
* 버그 수정

### 1.0.8 (2016년 6월 15일)

* SDK 초기화 관련 기능 개선

### 1.0.7 (2016년 6월 7일)

* AndroidManifest.xml에서 application 속성값 제거 (supportsRtl="true" 등)

### 1.0.6 (2016년 5월 18일)

* 버그 수정
* NullpointerException 보고에 대한 처리

### 1.0.5 (2016년 5월 18일)

* 요청부 쓰레드 적용
* 버그 수정

### 1.0.4 (2016년 5월 17일)

* 광고 표출에 대한 예외처리 강화
* 전면배너 로딩바 추가 (로딩시간 지연시 표출)
* 전면배너 표출시간 단축
* 버그 수정

### 1.0.3 (2016년 5월 9일)

* 에러코드 세분화
* 서버연동 관련 일부 수정
* 네트워크 타임아웃 관련 추가
* 버그 수정

### 1.0.2 (2016년 4월 29일)

* 하이브리드 앱 관련 대응
* 버그 수정

### 1.0.1 (2016년 4월 19일)

* 서버연동 관련 일부 수정

### 1.0.0 (2016년 3월 29일)

* 초기 버전


# 프로젝트 설정

### 1 : SDK 연동을 위한 준비

* Xcode 16.0 이상
* Deployment Target : iOS 12.0 이상

> 앱 스토어 커넥트에 업로드 날짜에 따른 빌드에 사용하는 Xcode 버전 요구사항은 다음과 같습니다.
>
> * 2025년 4월 24일부터: Xcode 16 이상
> * 2026년 4월 28일부터: Xcode 26 이상\
>   \
>   <https://developer.apple.com/kr/news>

### 2 : 설치

#### [`CocoaPods`](https://cocoapods.org) 사용

* AdPie SDK의 최신버전을 가져오려면 아래와 같이 프로젝트의 Podfile에 추가합니다.

```
  platform :ios, '12.0'
  use_frameworks!

  target YOUR_PROJECT_TARGET do
    pod 'AdPieSDK'
  end
```

* 터미널 실행하고 iOS 프로젝트가 있는 경로로 이동 후, 아래 명령어를 실행하여 AdPie SDK를 설치합니다.

```
  pod install --repo-update
```

#### [Swift Package Manager](https://swift.org/package-manager) 사용

* Xcode 실행 후, `Add Package Dependencies` 메뉴를 클릭합니다.

```
  Xcode > File > Add Package Dependencies....
```

* 프롬프트 창이 나타나면 아래의 Git Hub 저장소 URL를 사용하여 검색합니다.

```
  https://github.com/gomfactory/AdPie-iOS-SDK.git
```

* 설치하려는 버전을 선택하고 `Add Package` 버튼을 클릭하여 AdPie SDK를 설치합니다.

  > Swift Package Manager 를 이용하여 SDK를 설치하는 경우, AdPie SDK V1.6.3 버전부터 설치 가능.
* 아래의 `Xcode 프로젝트 설정` 내용을 참고하여 `Other Linker Flags` 설정을 완료합니다.

#### SDK 수동 설치

* SDK 및 샘플프로젝트를 [download](https://github.com/gomfactory/AdPie-iOS-SDK/archive/master.zip) 합니다.
* `AdPie-iOS-SDK-master.zip` 파일을 압축을 해제하고 `AdPieSDK.xcframework` 파일이 있는지 확인합니다.
* Xcode에서 타겟 프로젝트 선택 후, `General -> Frameworks, Libraries, and Embedded Content` 에 `AdPieSDK.xcframework` 파일을 드래그하여 추가합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FWC99VgUJWbuYsrwrhTJ2%2Fmanual_install.png?alt=media&amp;token=5f88c9cb-3b53-4b0b-aef1-3b0eea265293" alt=""><figcaption></figcaption></figure>

* 아래의 `Xcode 프로젝트 설정` 내용을 참고하여 `Other Linker Flags` 설정을 완료합니다.

#### Xcode 프로젝트 설정

* Xcode 실행 > 프로젝트 타겟 선택 > Build Settings에서 `Other Linker Flags` 에 `$(inherited)` 와 `-ObjC` 플래그가 추가되어 있는지 확인합니다.

  > 위의 플래그가 없을 경우 , 비정상 종료(Crash)가 발생할 수 있습니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FEtKufjzYtCtaOf9Ev2AT%2Fother_link_flag.png?alt=media&amp;token=97d14b29-1c04-412e-aae8-c9d4c5656133" alt=""><figcaption></figcaption></figure>

### 3 : iOS 14+ 대응

* [iOS 14+ 대응](https://github.com/gomfactory/AdPie-iOS-SDK/wiki/iOS-14-%EC%9D%B4%EC%83%81--%EB%8C%80%EC%9D%91) 페이지를 통해 info.plist 와 코드를 적용합니다.


# iOS 14+ 대응

### SKAdNetwork 구성

* 사용자의 ATT 동의 여부와 무관하게, 애플에서 공식으로 제공하는 광고 캠페인의 성공을 측정하기 위한 목적으로 SKAdNetwork를 도입하였으며 SKAdNetwork를 사용하기 위해서는 iOS 앱 프로젝트에 있는 Info.plist 파일에 광고 식별자 목록 정보를 아래와 같이 추가합니다.

```xml
<key>SKAdNetworkItems</key>
<array>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>v72qych5uu.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>x8uqf25wch.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>k674qkevps.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>9t245vhmpl.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>2u9pt9hc89.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>22mmun2rn5.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>hs6bdukanm.skadnetwork</string>
    </dict>
    
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>uw77j35x4d.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>32z4fx6l9h.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>8s468mfl3y.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>ln5gz23vtd.skadnetwork</string>
    </dict>    
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>5tjdwbrq8w.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>cstr6suwn9.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>4fzdc2evr5.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>v9wttpbfk9.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>zq4921623r.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>pwa73g5rt2.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>7ug5zh24hu.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>ns5j362hk7.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>e5fvkxwrpn.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>mqn7fxpca7.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>5a6flpkh64.skadnetwork</string>
    </dict>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>97r2b46745.skadnetwork</string>
    </dict>
</array>
```

### IDFA (Identifier for Advertisers)

* iOS 14.5 이전에는 '광고 추적 제한 (Limit Ad Tracking)'을 활성화하기 전에는 IDFA (Identifier for Advertisers) 값을 가져올 수 있습니다.
* iOS 14.5+ 부터는 사용자 권한 요청을 통해 사용을 허용한 경우에만 IDFA 값을 가져올 수 있습니다.
* 광고 수익이 줄어드는 것을 방지하려면 iOS 14+ 부터는 다음과 같이 변경해야 합니다.

### ATT (AppTrackingTransparency) 사용

* iOS 14.5 이상에서 IDFA 와 같은 식별자에 대한 액세스 및 사용에 대한 권한을 요청하려면 ATT (AppTrackingTransparency) 알림을 사용해야 합니다.
* 자세한 내용은 아래의 단계에 따라 진행해야 합니다.

#### Step 1:Info.plist 파일 적용 (권한 사용에 대한 설명 문구)

* `Info.plist` 파일에 `NSUserTrackingUsageDescription` 키와 권한 사용에 대한 동의를 구하는 메시지를 추가합니다.\
  &#x20;

  <figure><img src="https://raw.githubusercontent.com/wiki/gomfactory/AdPie-iOS-SDK/image/ios_sdk_att_setting.png" alt=""><figcaption></figcaption></figure>

(Example - English)

```xml
<key>NSUserTrackingUsageDescription</key>
<string>This identifier will be used to deliver personalized ads to you.</string>
```

(Example - 한글)

```xml
<key>NSUserTrackingUsageDescription</key>
<string>개인 맞춤 광고를 게재하는 데 사용됩니다.</string>
```

#### Step 2:코드 수정 (권한 요청)

* 기존에 애드파이 SDK 초기화 하기 전에 ATT 알림을 통한 권한을 요청합니다.
* 권한 요청 관련 메소드로 [requestTrackingAuthorizationWithCompletionHandler:](https://developer.apple.com/documentation/apptrackingtransparency/attrackingmanager/3547037-requesttrackingauthorization) 호출을 사용합니다.
* 앞서 설명한 Info.plist 파일에 `NSUserTrackingUsageDescription` 키에 설명 문구를 추가하지 않으면 Crash가 발생하니 유의합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}

#### 적용화면

| ![ATT 알림 샘플 (한글)](https://raw.githubusercontent.com/wiki/gomfactory/AdPie-iOS-SDK/image/ios_sdk_att_kor.png) | ![ATT 알림 샘플 (English)](https://raw.githubusercontent.com/wiki/gomfactory/AdPie-iOS-SDK/image/ios_sdk_att_eng.png) |
| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|                                                                                                              |                                                                                                                   |


# 광고 연동

{% content-ref url="/pages/4RA64FFxq374OaLqjqfT" %}
[배너 광고](https://platform-business.gitbook.io/adpie/ios/integration/banner)
{% endcontent-ref %}

{% content-ref url="/pages/EzLNXmwrdryXmuPwWr1j" %}
[전면 광고](https://platform-business.gitbook.io/adpie/ios/integration/interstitial)
{% endcontent-ref %}

{% content-ref url="/pages/FKYTmmRvhluKjaaCdd6m" %}
[네이티브 광고](https://platform-business.gitbook.io/adpie/ios/integration/native)
{% endcontent-ref %}

{% content-ref url="/pages/KGj8jJnnwL5rNyPuIPLA" %}
[리워드 비디오 광고](https://platform-business.gitbook.io/adpie/ios/integration/rewardedad)
{% endcontent-ref %}


# 배너 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/ios/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : SDK 초기화

* 최초 SDK 를 초기화 완료 후, 광고 요청이 가능합니다.
* [사이트](http://my.adpies.com)에서 발급받은 `Media ID`를 입력합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}

### 3 : 광고뷰 생성

* 띠배너 생성시 가로의 크기는 320 이상, 세로의 크기는 50으로 생성합니다. (가로는 디바이스 전체 너비를 추천합니다.)
* 띠배너의 경우 320 사이즈의 이미지로 가운데에 채워지고 나머지는 배경색으로 채워집니다.

#### 1. 프로그램 코드를 통한 생성

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
import UIKit
import AdPieSDK

class BannerAdViewContoller: UIViewController, APAdViewDelegate {

    var adView: APAdView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 세로는 50으로 고정
        adView.rootViewController = self
        adView.delegate = self
        view.addSubview(adView)
        adView.translatesAutoresizingMaskIntoConstraints = false
        let safeAreaGuide = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            adView.bottomAnchor.constraint(equalTo: safeAreaGuide.bottomAnchor),
            adView.leadingAnchor.constraint(equalTo: safeAreaGuide.leadingAnchor),
            adView.trailingAnchor.constraint(equalTo: safeAreaGuide.trailingAnchor),
            adView.heightAnchor.constraint(equalToConstant: 50)
        ])
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
#import <UIKit/UIKit.h>
#import <AdPieSDK/AdPieSDK.h>

@interface ViewController : UIViewController <APAdViewDelegate>
@property APAdView *adView;
@end

// ViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 오토 레이아웃, 세로는 50으로 고정
    [self.view addSubview:self.adView];
    self.adView.translatesAutoresizingMaskIntoConstraints = NO;
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.adView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor],
        [self.adView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor constant:10],
        [self.adView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor constant:-10],
        [self.adView.heightAnchor constraintEqualToConstant:50]
    ]];
}
```

{% endtab %}
{% endtabs %}

#### 2. 인터페이스 빌더(스토리 보드)를 통한 생성

1. `ViewController`에 `AdPie` 라이브러리를 임포트하고, `APAdViewDelegate`프로토콜을 도입(adopt)합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APAdViewDelegate {

}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
#import <UIKit/UIKit.h>
#import <AdPieSDK/AdPieSDK.h>

@interface ViewController : UIViewController <APAdViewDelegate>
@end
```

{% endtab %}
{% endtabs %}

2. 스토리 보드 파일에서 배너 광고를 표시할 UIView를 추가하고, Custom Class을 `APAdView`로 변경합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2F6G26wVctjw8AfH32VDkE%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202024-10-08%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%2010.24.20.png?alt=media&amp;token=94f8437c-d9ba-4a47-adfe-c5bae31cb24c" alt=""><figcaption></figcaption></figure>

2. 광고 뷰의 제약(Constraints)을 설정합니다.

* Ad View Width = Superview\.Width
* Ad View Height = 50,
* Ad View Center X = Superview\.Center X
* Ad View Bottom = Bottom Layout Top

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FOacVgxhmGx7mbgcUBILZ%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202024-10-08%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%2010.26.28.png?alt=media&amp;token=a1f3bb3e-7afc-43cb-9107-74b3fe03acc3" alt=""><figcaption></figcaption></figure>

4. 광고 뷰(UIView)를 노출 될 ViewController에 드래그하여 프로퍼티(IBOutlet)로 연결합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APAdViewDelegate {
    @IBOutlet weak var adView: APAdView!
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
#import <UIKit/UIKit.h>
#import <AdPieSDK/AdPieSDK.h>

@interface ViewController : UIViewController <APAdViewDelegate>

@property (weak) IBOutlet APAdView *adView;

@end
```

{% endtab %}
{% endtabs %}

### 4 : 광고 요청과 표출

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력합니다.
* 광고뷰의 RootViewController 를 등록해야 주기별로 광고 재요청을 합니다. (Refresh)
* 광고 호출에 대한 콜백이 필요한 경우 델리게이트를 등록하며, 자세한 사항은 하단을 참고합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()
        
    // 광고뷰에 Slot ID 입력
    adView.slotId = "YOUR_SLOT_ID_HERE"
    // 광고뷰의 RootViewController 등록 (Refresh를 위해 필요)
    adView.rootViewController = self
    // 델리게이트 등록
    adView.delegate = self
    // 광고 요청
    adView.load()
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];

    // 광고뷰에 Slot ID 입력
    self.adView.slotId = @"YOUR_SLOT_ID_HERE";
    // 광고뷰의 RootViewController 등록 (Refresh를 위해 필요)
    self.adView.rootViewController = self;
    // 델리게이트 등록
    self.adView.delegate = self;
    // 광고요청
    [self.adView load];
}
```

{% endtab %}
{% endtabs %}

### 5 : 광고 이벤트

* 광고 호출에 대한 콜백(이벤트)을 받을 수 있습니다.
* ViewController에서 `APAdViewDelegate` 프로토콜을 도입(adopt)합니다.
* 광고 뷰의 delegate 프로퍼티에 콜백(이벤트)를 수신받을 객체를 설정합니다.
* 델리게이트의 메소드 중 성공, 실패에 대한 메소드는 필수사항으로 반드시 구현해야 하며, 나머지 메소드는 필요에 따라서 구현합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/ios/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
import UIKit
import AdPieSDK

class ViewContorller: UIViewController, APAdViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        // 델리게이트 등록
        adView.delegate = self
    }

    // MARK: - APAdView delegates
    func adViewDidLoadAd(_ view: APAdView!) {
        // 광고 표출 성공 후 이벤트 발생
    }
    
    func adViewDidFail(toLoadAd view: APAdView!, withError error: Error!) {
        // 광고 요청 또는 표출 실패 후 이벤트 발생
        // error code : error._code
        // error message : error.localizedDescription
    }
    
    func adViewWillLeaveApplication(_ view: APAdView!) {
        // 광고 클릭 후 이벤트 발생
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.m
@implementation ViewController

- (void)adViewDidLoadAd:(APAdView *)view {
    // 광고 표출 성공 후 이벤트 발생
}

- (void)adViewDidFailToLoadAd:(APAdView *)view withError:(NSError *)error {
    // 광고 요청 또는 표출 실패 후 이벤트 발생
    // error code : [error code]
    // error message : [error localizedDescription]
}

- (void)adViewWillLeaveApplication:(APAdView *)view {
    // 광고 클릭 후 이벤트 발생
}

@end
```

{% endtab %}
{% endtabs %}


# 전면 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/ios/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : SDK 초기화

* 최초 SDK 를 초기화 완료 후, 광고 요청이 가능합니다.
* [사이트](http://my.adpies.com)에서 발급받은 `Media ID`를 입력합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}

### 3 : 광고 요청

* ViewController에 광고 요청을 위한 객체를 생성합니다.
* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있기에, 요청을 미리하고 표출을 필요할 때 합니다.(Preload)

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APInterstitialDelegate {

    var interstitial: APInterstitial!
    
    override func viewDidLoad() { 
        super.viewDidLoad()
        // 광고 객체 생성 (Slot ID 입력)
        interstitial = APInterstitial(slotId: "YOUR_SLOT_ID_HERE")
        // 델리게이트 등록
        interstitial.delegate = self
        // 광고 요청
        interstitial.load()
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
#import <AdPieSDK/AdPieSDK.h>

@interface ViewController : UIViewController <APInterstitialDelegate>
@property APInterstitial *interstitial;
@end

// ViewController.m
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 광고 객체 생성 (Slot ID 입력)
    self.interstitial = 
        [[APInterstitial alloc] initWithSlotId:@"YOUR_SLOT_ID_HERE"];
    // 델리게이트 등록
    self.interstitial.delegate = self;
    // 광고 요청
    [self.interstitial load];
}

@end
```

{% endtab %}
{% endtabs %}

### 4 : 광고 표출 (광고 이벤트 수신)

* 광고 호출에 대한 콜백을 받을 수 있습니다.
* ViewController에서 `APInterstitialDelegate` 프로토콜을 도입(adopt)합니다.
* 광고 객체의 delegate 프로퍼티에 콜백(이벤트)를 수신받을 객체를 설정합니다.
* 델리게이트의 메소드 중 성공, 실패에 대한 메소드는 필수사항으로 반드시 구현해야 하며, 나머지 메소드는 필요에 따라서 구현합니다.
* 광고를 요청하기 위해서는 `load`를 호출하고, 표출하기 위해서는 swift에서는 `present` 메소드를 호출하고, Objective-C 언어에서는  `presentFromRootViewController:` 메소드를 호출합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/ios/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

{% tabs %}
{% tab title="Swift" %}

<pre class="language-swift"><code class="lang-swift">import UIKit
import AdPieSDK

class ViewController: UIViewController, APInterstitialDelegate {

    ...
        
    // MARK: - APInterstitial delegates    
    func interstitialDidLoadAd(_ interstitial: APInterstitial!) {
        // 광고 로딩 완료 후 이벤트 발생 (성공)
        
        // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
        if interstitial.isReady() {
            // 광고 표출
            interstitial.present(fromRootViewController: self)
        }
    }
    
    func interstitialDidFail(toLoadAd interstitial: APInterstitial!, withError error: Error!) {
        // 광고 요청 실패 후 이벤트 발생
        // error code : error._code
        // error message : error.localizedDescription
    }
    
    func interstitialDidFail(toShowAd interstitial: APInterstitial!, withError error: (any Error)!) {
        // 광고 표출 실패
    }
    
    func interstitialWillPresentScreen(_ interstitial: APInterstitial!) {
        // 광고 표출 후 이벤트 발생
    }
    
    func interstitialWillDismissScreen(_ interstitial: APInterstitial!) {
        // 광고가 표출한 뒤 종료하기 전에 이벤트 발생
    }
    
    func interstitialDidDismissScreen(_ interstitial: APInterstitial!) {
        // 광고가 표출한 뒤 종료한 후 이벤트 발생
    }
    
    func interstitialWillLeaveApplication(_ interstitial: APInterstitial!) {
        // 광고 클릭 후 이벤트 발생
    }
    
<strong>    func videoFinished(_ interstitial: APInterstitial!, videoFinishState: APVideoFinishState) {
</strong>        // 동영상 광고 종료 알림 (iOS AdPie SDK 1.6.10 지원)
        switch videoFinishState {
        case .error:
            print("동영상 광고 오류")
        case .skipped:
            print("동영상 광고 건너뜀")
        case .completed:
            print("동영상 광고 시청완료")
        default:
            break
    }
}
</code></pre>

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.m
@implementation ViewController

#pragma mark APInterstitial delegates

- (void)interstitialDidLoadAd:(APInterstitial *)interstitial {
    // 광고 로딩 완료 후 이벤트 발생 (성공)
    // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
    if ([self.interstitial isReady]) {
        // 광고 표출
        [self.interstitial presentFromRootViewController:self];
    }
}

- (void)interstitialDidFailToLoadAd:(APInterstitial *)interstitial 
    withError:(NSError *)error 
{
    // 광고 요청 실패 후 이벤트 발생
    // error code : [error code]
    // error message : [error localizedDescription]
}

- (void)interstitialDidFailToShowAd:(APInterstitial *)interstitial 
   withError:(NSError *)error 
{
    // 광고 표출 실패
}

- (void)interstitialWillPresentScreen:(APInterstitial *)interstitial {
    // 광고 표출 후 이벤트 발생
}

- (void)interstitialWillDismissScreen:(APInterstitial *)interstitial {
    // 광고가 표출한 뒤 종료하기 전에 이벤트 발생
}

- (void)interstitialDidDismissScreen:(APInterstitial *)interstitial {
    // 광고가 표출한 뒤 종료한 후 이벤트 발생
}

- (void)interstitialWillLeaveApplication:(APInterstitial *)interstitial {
    // 광고 클릭 후 이벤트 발생
}

- (void)videoFinished:(APInterstitial *)interstitial videoFinishState:(APVideoFinishState)finishState {
    // 동영상 광고 종료 알림 (iOS AdPie SDK 1.6.10 지원)
    switch (videoFinishState) {
        case APVideoFinishStateError:       break;  // 동영상 광고 오류
        case APVideoFinishStateSkipped:     break;  // 동영상 광고 건너띔
        case APVideoFinishStateCompleted:   break;  // 동영상 광고 시청완료
        default:
            break;
    }
}

@end
```

{% endtab %}
{% endtabs %}


# 네이티브 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/ios/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : SDK 초기화

* 최초 SDK 를 초기화 완료 후, 광고 요청이 가능합니다.
* [사이트](http://my.adpies.com)에서 발급받은 `Media ID`를 입력합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}

### 3 : 레이아웃 관련 설정

#### 1. 광고요소 선택

* 네이티브 광고의 요소 (**`① 아이콘`** **`② 제목`** **`③ 설명`** **`④ 메인`** `⑤ 액션버튼`) 중 사용할 요소를 미리 결정합니다.
* 단, `① 아이콘` `② 제목` `③ 설명` `④ 메인` 중 최소 하나는 필수적으로 들어가야 하며, 선택한 요소에 따라 광고 물량에 차이가 발생합니다.
* `⑤ 액션버튼` 이 없을 때보다 있을 때 CTR이 높게 나오기에 가능한 넣는 것을 추천합니다.
* `⑥ 옵트아웃` 은 자동으로 우측 상단에 붙이고 있기에 텍스트 영역과 겹치지 않도록 고려해야 합니다. (옵트아웃 이미지 크기 : 20, 상단 및 우측 여백 : 5)

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FpUVAKMfiNPUyRHzYi8pN%2Fclash.jpg?alt=media&amp;token=7868df0a-7d11-4d7f-8d44-a9ab7bf5d290" alt="" width="245"><figcaption></figcaption></figure>

<figure><img src="https://github.com/gomfactory/AdPie-iOS-SDK/wiki/image/ios_sdk_native_sample.png" alt="" width="375"><figcaption></figcaption></figure>

* 대시보드를 통해 슬롯을 생성하는 과정에서 슬롯유형에 네이티브(Native)를 선택하고, 네이티브 유형을 체크 합니다.
* 네이티브 유형은 앞서 선택한 필수 요소 (`① 아이콘` `② 제목` `③ 메인` `④ 설명`)에 해당됩니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FdPcoCQFOr6vWknDD5BsQ%2Fios_sdk_native_type.png?alt=media&amp;token=4c4e8265-668a-4206-93e9-198c5449a4c5" alt=""><figcaption></figcaption></figure>

* 체크한 유형은 XIB 파일에 필수로 들어가야 광고를 성공적으로 받아볼 수 있습니다.

#### 2. xib 파일에 광고의 요소 배치&#x20;

<figure><img src="https://github.com/gomfactory/AdPie-iOS-SDK/wiki/image/ios_sdk_native_xib_1.png" alt=""><figcaption></figcaption></figure>

* 네이티브 광고 템플릿 파일인 [AdPieNativeAdView.xib](https://github.com/gomfactory/AdPie-iOS-SDK/blob/master/AdPieSample/AdPieSample/AdPieNativeAdView.xib)를 참고하여 원하는 형태로 레이아웃을 구성합니다.

### 4 : 광고 요청

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력합니다.
* 광고 호출에 대한 콜백이 필요하기에 델리게이트를 등록하며, 자세한 사항은 하단을 참고합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
class NativeAdViewController: UIViewController, APNativeDelegate {
    
    var nativeAd: APNativeAd!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Slot ID 입력
        nativeAd = APNativeAd(slotId: "YOUR_SLOT_ID_HERE")
        // 델리게이트 등록
        nativeAd.delegate = self
        // 광고 요청
        nativeAd.load()
    }
       
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
@interface ViewController : UIViewController
@property (strong) APNativeAd *nativeAd;
@end

// ViewController.m
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 광고 객체 생성 (Slot ID 입력)
    self.nativeAd = 
        [[APNativeAd alloc] initWithSlotId:@"YOUR_SLOT_ID_HERE"];
    // 델리게이트 등록
    self.nativeAd.delegate = self;
    // 광고 요청
    [self.nativeAd load];
}

@end
```

{% endtab %}
{% endtabs %}

### 5 : 광고 표출 (광고 이벤트 수신)

* 광고 호출에 대한 콜백을 받을 수 있습니다.
* ViewController에서 `APNativeDelegate` 프로토콜을 도입(adopt)합니다.
* 광고 객체의 delegate 프로퍼티에 콜백(이벤트)를 수신받을 객체를 설정합니다.
* 델리게이트의 메소드 중 성공, 실패에 대한 메소드는 필수사항으로 반드시 구현해야 하며, 나머지 메소드는 필요에 따라서 구현합니다.
* 광고를 성공적으로 수신한다면, 앞서 생성한 xib 파일을 통해 광고뷰(`APNativeAdView`)를 생성합니다.
* `fillAd`메소드를 호출하여 광고뷰에 광고 데이터를 채웁니다.
* [에러코드](https://platform-business.gitbook.io/adpie/ios/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

{% tabs %}
{% tab title="Swift" %}

```swift
// ViewController.swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APNativeDelegate {

    ... 
    
    // MARK: - APNative delegates
    func nativeDidLoad(_ nativeAd: APNativeAd!) {
        // 광고 요청 완료 후 이벤트 발생 (성공)
        
        // 네이티브 광고뷰 생성 및 추가
        let nativeAdView = 
            Bundle.main.loadNibNamed("AdPieNativeAdView", 
                owner: nil, 
                options: nil)?[0] as! APNativeAdView
        view.addSubview(nativeAdView)
       
        // 제약 생성 및 적용 
        var viewDictionary = [String: AnyObject]()
        viewDictionary["nativeAdView"] = nativeAdView
            
        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "H:|[nativeAdView]|", 
                options: [], 
                metrics: nil, 
                views: viewDictionary))
        
        view.addConstraints(
            NSLayoutConstraint.constraints(
                withVisualFormat: "V:|[nativeAdView]|", 
                options: [], 
                metrics: nil, 
                views: viewDictionary))
        
        // 광고뷰에 데이터 표출
        if nativeAdView.fillAd(nativeAd.nativeAdData) {
            // 광고 클릭 이벤트 수신을 위해 등록
            nativeAd.registerView(forInteraction: nativeAdView)
        } else {
            nativeAdView.removeFromSuperview()
        }
    }
    
    func nativeDidFail(toLoad nativeAd: APNativeAd!, withError error: Error!) {
        // 광고 요청 실패 후 이벤트 발생
        // error code : error._code
        // error message : error.localizedDescription
    }
    
    func nativeWillLeaveApplication(_ nativeAd: APNativeAd!) {
        // 광고 클릭 후 이벤트 발생
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.m
@implementation ViewController

#pragma mark APNativeAd delegates

- (void)nativeDidLoadAd:(APNativeAd *)nativeAd {
    // 광고 요청 완료 후 이벤트 발생 (성공)

    // 네이티브 광고뷰 생성 및 추가
    APNativeAdView *nativeAdView = 
        [[[NSBundle mainBundle] loadNibNamed:@"AdPieNativeAdView"
            owner:nil
            options:nil] firstObject];
    
    [self.view addSubview:nativeAdView];
    
    // 제약 생성 및 적용
    NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(nativeAdView);
    [self.view addConstraints:[NSLayoutConstraint 
        constraintsWithVisualFormat:@"H:|[nativeAdView]|"
        options:0
        metrics:nil
        views:viewDictionary]];
        
    [self.view addConstraints:[NSLayoutConstraint 
        constraintsWithVisualFormat:@"V:|[nativeAdView]|"
        options:0
        metrics:nil
        views:viewDictionary]];
    
    // 광고뷰에 데이터 표출
    if ([nativeAdView fillAd:nativeAd.nativeAdData]) {
        // 광고 클릭 이벤트 수신을 위해 등록
        [nativeAd registerViewForInteraction:nativeAdView];
    } else {
        // 광고 데이터를 채우는데 실패한 경우로 광고뷰 제거
        [nativeAdView removeFromSuperview];
    }
}

- (void)nativeDidFailToLoadAd:(APNativeAd *)nativeAd
                          withError:(NSError *)error {

    // 광고 요청 실패 후 이벤트 발생
    // error code : [error code]
    // error message : [error localizedDescription]
}

- (void)nativeWillLeaveApplication:(APNativeAd *)nativeAd {
    // 광고 클릭 후 이벤트 발생
}

@end
```

{% endtab %}
{% endtabs %}

<img src="https://github.com/gomfactory/AdPie-iOS-SDK/wiki/image/ios_sdk_native_sample2.png" alt="네이티브 샘플" width="375">


# 리워드 비디오 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/ios/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : SDK 초기화

* 앱 구동시 최초 SDK 를 초기화하여야 광고 요청이 가능합니다.
* [사이트](http://my.adpies.com)에서 발급받은 `Media ID`를 입력합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}

### 3 : 광고 요청

* ViewController에 광고 요청을 위한 객체를 생성합니다.
* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있기에, 요청을 미리하고 표출을 필요할 때 합니다.(Preload)

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APRewardedAdDelegate {

    var rewardedAd: APRewardedAd!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 광고 객체 생성 (Slot ID 입력)
        rewardedAd = APRewardedAd(slotId: "YOUR_SLOT_ID_HERE")
        // 델리게이트 등록
        rewardedAd.delegate = self
        // 광고 요청
        rewardedAd.load()
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.h
#import <AdPieSDK/AdPieSDK.h>

@interface ViewController : UIViewController <APRewardedAdDelegate>
@property APRewardedAd *rewardedAd;
@end

// ViewController.m
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 광고 객체 생성 (Slot ID 입력)
    self.rewardedAd = 
        [[APRewardedAd alloc] initWithSlotId:@"YOUR_SLOT_ID_HERE"];
    // 델리게이트 등록
    self.rewardedAd.delegate = self;
    // 광고 요청
    [self.rewardedAd load];
}

@end
```

{% endtab %}
{% endtabs %}

### 4 : 광고 표출 (광고 이벤트 수신)

* 광고 호출에 대한 콜백을 받을 수 있습니다.
* ViewController에서 `APRewardedAdDelegate` 프로토콜을 도입(adopt)합니다.
* 광고 객체의 delegate 프로퍼티에 콜백(이벤트)를 수신받을 객체를 설정합니다.
* 델리게이트의 메소드 중 성공, 실패에 대한 메소드는 필수사항으로 반드시 구현해야 하며, 나머지 메소드는 필요에 따라서 구현합니다.
* 광고를 요청하기 위해서는 `load`를 호출하고, 표출하기 위해서는 swift에서는 `present` 메소드를 호출하고, Objective-C 언어에서는  `presentFromRootViewController:` 메소드를 호출합니다.
* [에러코드](https://platform-business.gitbook.io/adpie/ios/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK

class ViewController: UIViewController, APRewardedAdDelegate {
    ...
    // MARK: - APRewardedAd delegates
    func rewardedAdDidLoad(_ rewardedAd: APRewardedAd!) {
        // 광고 로딩 완료 후 이벤트 발생
        
        // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
        if rewardedAd.isReady() {
            // 광고 표출
            rewardedAd.present(fromRootViewController: self)
        }
    }
    
    func rewardedAdDidFail(toLoad rewardedAd: APRewardedAd!, 
        withError error: Error!) 
    {
        // 광고 요청 실패 후 이벤트 발생
        // error code : error._code
        // error message : error.localizedDescription
    }
    
    func rewardedAdDidFail(toShow rewardedAd: APRewardedAd!, 
     withError error: Error!) 
    {
        // 광고 표출 실패
    }
    
    func rewardedAdWillPresentScreen(_ rewardedAd: APRewardedAd!) {
        // 광고 표출 이벤트 발생
    }
    
    func rewardedAdWillDismissScreen(_ rewardedAd: APRewardedAd!) {
        // 광고가 표출한 뒤 종료하기 전에 이벤트 발생
    }
    
    func rewardedAdDidDismissScreen(_ rewardedAd: APRewardedAd!) {
        // 광고가 표출한 뒤 종료한 후 이벤트 발생
    }
    
    func rewardedAdDidEarnReward(_ rewardedAd: APRewardedAd!) {
        // 리워드광고 보상 이벤트 발생
    }
    
    func rewardedAdWillLeaveApplication(_ rewardedAd: APRewardedAd!) {
        // 광고 클릭 후 이벤트 발생
    } 
    
    func rewardedVideoFinished(_ rewardedAd: APRewardedAd!, videoFinishState: APVideoFinishState) {
        // 동영상 광고 종료 알림 (iOS AdPie SDK 1.6.10 지원)
        switch videoFinishState {
        case .error:
            print("동영상 광고 오류")
        case .skipped:
            print("동영상 광고 건너뜀")
        case .completed:
            print("동영상 광고 시청완료")
        default:
            break
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ViewController.m
@implementation ViewController

#pragma mark APRewardedAd delegates

- (void)rewardedAdDidLoadAd:(APRewardedAd *)rewardedAd {
    // 광고 로딩 완료 후 이벤트 발생 (성공)
    // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
    if ([self.rewardedAd isReady]) {
        // 광고 표출
        [self.rewardedAd presentFromRootViewController:self];
    }
}

- (void)rewardedAdDidFailToLoadAd:(APRewardedAd *)rewardedAd
                          withError:(NSError *)error {
    // 광고 요청 실패 후 이벤트 발생
    // error code : [error code]
    // error message : [error localizedDescription]
}

- (void)rewardedAdDidFailToShowAd:(APRewardedAd *)rewardedAd 
                          withError:(NSError *)error {
    // 광고 표출 실패
}

- (void)rewardedAdWillPresentScreen:(APRewardedAd *)rewardedAd {
    // 광고 표출 이벤트 발생
}

- (void)rewardedAdWillDismissScreen:(APRewardedAd *)rewardedAd {
    // 광고가 표출한 뒤 종료하기 전에 이벤트 발생
}

- (void)rewardedAdDidDismissScreen:(APRewardedAd *)rewardedAd {
    // 광고가 표출한 뒤 종료한 후 이벤트 발생
}

- (void)rewardedAdDidEarnReward:(APRewardedAd *)rewardedAd {
    // 리워드광고 보상 이벤트 발생
}

- (void)rewardedAdWillLeaveApplication:(APRewardedAd *)rewardedAd {
    // 광고 클릭 후 이벤트 발생
}

- (void)rewardedVideoFinished:(APRewardedAd *)rewardedAd videoFinishState:(APVideoFinishState)finishState {
    // 동영상 광고 종료 알림 (iOS AdPie SDK 1.6.10 지원)
    switch (videoFinishState) {
        case APVideoFinishStateError:       break;  // 동영상 광고 오류
        case APVideoFinishStateSkipped:     break;  // 동영상 광고 건너띔
        case APVideoFinishStateCompleted:   break;  // 동영상 광고 시청완료
        default:
            break;
    }
}

@end

```

{% endtab %}
{% endtabs %}


# 미디에이션

{% content-ref url="/pages/qeikLVXqEw0bCKYvt4eU" %}
[구글 애드몹](https://platform-business.gitbook.io/adpie/ios/mediation/admob)
{% endcontent-ref %}

{% content-ref url="/pages/ohX7umDrQIITRXMXUd5G" %}
[구글 애드 매니저](https://platform-business.gitbook.io/adpie/ios/mediation/admanager)
{% endcontent-ref %}

{% content-ref url="/pages/9KNi7VuUo9TtRht3CL1B" %}
[앱러빈](https://platform-business.gitbook.io/adpie/ios/mediation/applovin)
{% endcontent-ref %}


# 구글 애드몹

구글 애드몹의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : 미디에이션 추가 준비

* AdPie SDK 버전 1.4.5 이상

### 2 : Custom Event 클래스 추가

* 샘플 앱 [다운로드](https://github.com/gomfactory/AdPie-iOS-SDK/archive/master.zip)
* 압축 해제 후, Mediations 디렉토리 > AdMobAdapterAdpie 디렉토리가 존재하는지 확인합니다.
* 개발중인 Xcode 프로젝트를 열고, "AdMobAdapterAdpie" 디렉토리를 Xcode 프로젝트로 드래그하여 추가합니다.

### 3 : 미디에이션 등록(Custom Event)

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [Custom Event](https://support.google.com/admob/answer/3083407?ctx=tltp\&hl=ko) 를 확인합니다.
* 1\) [애드몹](https://apps.admob.com) 사이트 통해 로그인을 합니다.
* 2\) 사이드바에서 **미디에이션**을 클릭합니다.
* 3\) 미디에이션 그룹의 이름을 클릭합니다.
* 4\) 폭포식 구조 광고 소스 표의 **맞춤 이벤트** 추가를 클릭합니다.
* 5\) 이벤트를 설명하는 라벨을 입력합니다.
* 6\) 이 맞춤 이벤트에 사용할 수동 eCPM을 입력합니다.
* **7) 계속**을 클릭합니다.
* 8\) 각 광고 단위의 **클래스 이름(필수)** 및 **매개변수(선택사항)** 를 입력합니다.

> Class Name 에는 광고 유형에 맞게 아래의 클래스 이름을 입력합니다.

* AdMobAdPieBannerAd: 배너(Banner) 광고용 클래스
* AdMobAdPieInterstitialAd: 전면(Interstitial) 광고용 클래스
* AdMobAdPieRewardedAd: 보상(Reward) 광고용 클래스

> Parameter(선택사항) 정보에는 AdPie에서 발급받은 **Media ID**와 **Slot ID**를 `{"app_id":"Insert_Media_ID", "slot_id":"Insert_Slot_ID"}` 형식으로 입력합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FSxuOSX13884BiFvrjpuf%2Fadmob_dashboard_2.png?alt=media&amp;token=4c42c976-1663-49a5-89b7-ab872e352972" alt=""><figcaption></figcaption></figure>

* **9) 완료** 버튼을 클릭합니다.
* **10) 저장** 버튼을 클릭합니다.


# 구글 애드 매니저

구글 애드 매니저의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : 미디에이션 추가 준비

* AdPie SDK 버전 1.4.5 이상

### 2 : Custom Event 클래스 추가

* 샘플 앱 [다운로드](https://github.com/gomfactory/AdPie-iOS-SDK/archive/master.zip)
* 압축 해제 후, Mediations 디렉토리 > AdMobAdapterAdpie 디렉토리가 존재하는지 확인합니다.
* 개발중인 Xcode 프로젝트를 열고, "AdMobAdapterAdpie" 디렉토리를 Xcode 프로젝트로 드래그하여 추가합니다.

### 3 : 미디에이션 등록

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [미디에이션](https://support.google.com/admanager/answer/6272813?hl=ko\&sjid=17829723247869263806-AP) 를 확인합니다.
* 1\) [애드 매니저](https://admanager.google.com) 사이트 통해 로그인을 합니다.
* 2\) 수익 파트너 등록이 되어 있지 않으면 아래와 같이 등록합니다.
* ```
  (1) 관리 > 업체을 클릭합니다.
  (2) 새 회사를 클릭합니다.
  (3) 광고 네트워크를 선택합니다.
  (4) 이름에 'AdPie'로 입력합니다.
  (5) 광고 네트워크에서 'MoPub'을 선택하고 미디에이션을 활성화합니다.
  (6) 저장을 클릭합니다.
  ```
* 3\) 수익 그룹이 등록되어 있지 않으면 아래와 같이 등록합니다.
* ```
  (1) 게재 > 수익 그룹을 클릭합니다.
  (2) 새 수익 그룹을 클릭합니다.
  (3) 보고를 위해 알아보기 쉬운 고유한 수익 그룹 이름을 입력합니다.
  (4) 수익 그룹으로 타겟팅하려는 광고 형식과 인벤토리 유형을 선택합니다.
  (5) 저장을 클릭합니다.
  ```
* 4\) 수익 그룹에서 AdPie를 수익파트너로 추가합니다.
* ```
  (1) 게재 > 수익 그룹을 클릭합니다.
  (2) 수정할 수익 그룹의 이름을 클릭합니다.
  (3) 수익 파트너 추가를 클릭합니다.
  (4) 수익 파트너 드롭다운에서 앞에서 등록한 'AdPie' 수익 파트너를 선택합니다.
  (5) 통합 유형을 '맞춤 이벤트'로 기본 설정 확인합니다.
  (6) 타겟팅하려는 플랫폼(iOS)을 선택합니다.
  (7) 상태 ('운영중' 또는 '비활성화')를 선택합니다.
  (8) 기본 CPM을 입력합니다.
  (9) 추가 수익 파트너 세부 정보를 입력합니다. (자세한 내용은 아래 참고합니다.)
  (10) 저장을 클릭합니다.
  ```

> Label은 구분하기 쉬운 값을 입력합니다.

> Class Name 에는 광고 유형에 맞게 아래의 클래스 이름을 입력합니다.

* AdMobAdPieBannerAd: 배너(Banner) 광고용 클래스
* AdMobAdPieInterstitialAd: 전면(Interstitial) 광고용 클래스
* AdMobAdPieRewardedAd: 보상(Reward) 광고용 클래스

> Parameter(선택사항) 정보에는 AdPie에서 발급받은 **Media ID**와 **Slot ID**를 `{"app_id":"Insert_Media_ID", "slot_id":"Insert_Slot_ID"}` 형식으로 입력합니다.

<div align="left"><figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2F5mV2hcyu4tfhCpmFkXOe%2Fadmob_dashboard_3.png?alt=media&amp;token=de2bb4d7-d35c-42fb-850e-be3168219ff8" alt=""><figcaption></figcaption></figure></div>


# 앱러빈

앱러빈의 미디에이션 중 하나의 애드 네트워크(Ad Network)로 구성할 수 있습니다.

### 1 : 미디에이션 추가 준비

* AdPie SDK 버전 1.4.5 이상

### 2 : Custom Event 클래스 추가

* 샘플 앱 [다운로드](https://github.com/gomfactory/AdPie-iOS-SDK/archive/master.zip)
* 압축 해제 후, Mediations 디렉토리 > AppLovinAdapterAdPie 디렉토리가 존재하는지 확인합니다.
* 개발중인 Xcode 프로젝트를 열고, "AppLovinAdapterAdPie" 디렉토리를 Xcode 프로젝트로 드래그하여 추가합니다.

### 3 : 미디에이션 등록(Custom Event)

* 아래의 절차대로 진행을 해야 하며, 자세한 사항은 [Custom SDK Network Integration Guide](https://dash.applovin.com/documentation/mediation/android/mediation-setup/custom-sdk) 를 확인합니다.
* 1\) [앱러빈](https://www.applovin.com) 사이트에서 로그인을 합니다.
* 2\) 사이드바에서 [MAX > Mediation > Manage > Networks](https://dash.applovin.com/o/mediation/networks/) 를 선택합니다.
* 3\) 페이지 하단에 있는 **Click here to add a Custom Network**를 클릭합니다.
* 4\)Network Type은 **SDK**를 선택하고 Custom Network 이름을 입력합니다.
* 5\) iOS Adapter Class Name에 `AppLovinAdPieAdapter`를 입력합니다.

  > AppLovinAdPieAdapter: \
  > 배너(Banner), 전면(Interstitial), 보상(Reward), 네이티브(Native) 광고용 클래스

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2Fb2a21FgVBmK6xxUIp9xV%2Fapplovin_dashboard_2.png?alt=media&amp;token=ae1b2e99-c88f-47f5-888e-d2f609c2a60f" alt=""><figcaption></figcaption></figure>

* 6\) 저장 (Save)를 클릭합니다.
* 7\) [MAX > Mediation > Manage > Ad Units](https://dash.applovin.com/o/mediation/ad_units/) 에서 AdPie를 추가할 Ad Unit을 선택합니다.
* **8) App ID (optional)** 에 AdPie에서 발급받은 `Media ID` 를 입력하고, **Placement ID** 에는 `Slot ID`를 입력합니다.

<figure><img src="https://1072946756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh39HnaSiiPTrGCntZMCm%2Fuploads%2FOfzvlHrijoJBzqD6knvW%2Fapplovin_dashboard_4.png?alt=media&amp;token=5b53f11d-d1a3-4a07-a5d1-a2ef95591093" alt=""><figcaption></figcaption></figure>

* 9\) 저장 (Save)를 클릭합니다.


# 공통

{% content-ref url="/pages/c9VMqQrmeJS7K0id30N4" %}
[에러코드](https://platform-business.gitbook.io/adpie/ios/common/errorcode)
{% endcontent-ref %}

{% content-ref url="/pages/BVGdCH4ESNejvHmDYkMZ" %}
[디버깅](https://platform-business.gitbook.io/adpie/ios/common/debug)
{% endcontent-ref %}

{% content-ref url="/pages/MiRm6iN43PUdUIsdaFC6" %}
[Broken mention](broken://pages/MiRm6iN43PUdUIsdaFC6)
{% endcontent-ref %}

{% content-ref url="/pages/6P77j8trAuQ4uZwztnaB" %}
[변경내역](https://platform-business.gitbook.io/adpie/ios/changelog)
{% endcontent-ref %}


# 에러코드

* SDK를 통한 광고 실패에 대한 코드와 메시지는 아래와 같이 정의되어 있습니다.

|  code | message                                           | description                                                       |
| :---: | ------------------------------------------------- | ----------------------------------------------------------------- |
| `100` | No fill.                                          | 광고 없음                                                             |
| `101` | Invalid ad request.                               | 잘못된 요청 파라미터 (Media ID, Slot ID, Bundle ID 확인)                     |
| `102` | A network error occurred.                         | 네트워크 오류 (서버통신 오류, 지속시 문의필요)                                       |
| `103` | No internet connection detected.                  | 연결된 인터넷 정보 없음 (인터넷 연결상태 확인)                                       |
| `104` | An internal error occurred.                       | 내부 오류 (발생시 문의필요)                                                  |
| `105` | AdPie SDK must be initialized before ads loading. | SDK 초기화 미완료 (연동 실패)                                               |
| `106` | Previous ad request is being processed.           | 중복 요청 (기존 요청이 끝나기전에 재요청)                                          |
| `107` | An error occurred while loading content.          | 컨텐츠 로딩 오류 (웹뷰의 컨텐츠 로딩실패)                                          |
| `108` | A server data error occurred.                     | 서버 데이터 오류 (데이터 파싱, 지속시 문의필요)                                      |
| `109` | Invalid ad layout.                                | 레이아웃 설정 오류 (배너의 경우 백그라운드 상태이거나 잘못된 슬롯 사이즈, 네이티브의 경우 필수 요소가 빠진 상태) |
| `110` | Ad request was blocked with minimum time limit.   | 광고 요청의 시간 제한 (기존 요청의 시간 비교 후 서버 전송 없음)                            |


# 디버깅

* 연동 과정에서 디버깅을 필요하다면, 아래와 같이 코드를 적용하여 '\[ADPIE]'를 포함하는 텍스트를 검색하여 로그 메시지를 확인합니다.

{% tabs %}
{% tab title="Swift" %}

```swift
import UIKit
import AdPieSDK
import AppTrackingTransparency

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    {
        return true
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

        func initializeSDK() {
            // 디버깅 적용
            AdPieSDK.sharedInstance().logging()
            // SDK 초기화
            AdPieSDK.sharedInstance().initWithMediaId("YOUR_MEDIA_ID")
        }
    
        if #available(iOS 14.5, *) {
            ATTrackingManager.requestTrackingAuthorization { _ in
                initializeSDK()
            }
        } else {
            initializeSDK()
        }
    }
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// AppDelegate.m
#import "AppDelegate.h"
#import <AdPieSDK/AdPieSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (@available(iOS 14.5, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(_){
            [self initializeSDK];
        }];
    } else {
        [self initializeSDK];
    }
}

- (void)initializeSDK {
    // 디버깅 적용
    [[AdPieSDK sharedInstance] logging];
    // SDK 초기화
    [[AdPieSDK sharedInstance] initWithMediaId:@"YOUR_MEDIA_ID_HERE"];
}

@end
```

{% endtab %}
{% endtabs %}


# 샘플 애플리케이션

* Objective-C 샘플 애플리케이션

{% embed url="<https://github.com/gomfactory/AdPie-iOS-SDK/tree/master/AdPieSample>" %}

* Swift 샘플 애플리케이션

{% embed url="<https://github.com/gomfactory/AdPie-iOS-SDK/tree/master/AdPieSwiftSample>" %}


# 변경내역

### 1.7.1 (2026년 07월 27일)

* 개발자 로그 활성화 및 출력 개선
* 보상/전면 광고가 닫힌 후에도 내부 상태가 SHOW로 남아있던 문제 수정
* 보상/전면 광고의 SID(Slot ID) 프로퍼티를 READ-ONLY로 변경

### 1.7.0 (2026년 07월 15일)

* UA (UgerAgent) 정보를 가져오는 방식 변경
* 광고 요청 관련 DATA RACE 방지 (쓰레드 세이프)
* SSV 관련 데이터 설정을 광고 로드 이후에도 변경할 수 있도록 허용
* 콘솔 로그 관련 버그 수정
* UI 및 SDK 성능 개선

### 1.6.16 (2026년 03월 16일)

* SDK 안정성 개선

### 1.6.15 (2026년 01월 21일)

* 전면 광고 및 보상형 광고 노출 실패 델리게이트 추가
* 비디오 캐시 기능 추가 (비디오 재생 속도 개선)

### 1.6.14 (2025년 12월 04일)

* 배너/전면/보상 광고용 "onPaidEvent" 추가

### 1.6.13 (2025년 09월 22일)

* 초기화 메소드 "initWithMediaId:withData:completion:" 추가

### 1.6.12 (2025년 09월 17일)

* 개발자 로그 활성화 로직 개선

### 1.6.11 (2025년 08월 04일)

* 닫기 버튼 클릭 시, 비디오 재생 완료 이벤트 전달

> 기존: 비디오 재생 완료 시점에, 비디오 재생 완료 이벤트 전달

### 1.6.10 (2025년 07월 25일)

* 전면/비디오 광고에 비디오 종료 상태 전달용 신규 메서드 추가

  &#x20;rewardedVideoFinished:videoFinishState:&#x20;

  &#x20;videoFinished:videoFinishState:

> 1.6.9 버전에서 추가된 전면/비디오 광고용 비디오 종료 상태 메서드는 제거

### 1.6.9 (2025년 07월 18일)

* 전면/비디오 광고에 비디오 종료 상태 알림 이벤트 추가

### 1.6.8 (2025년 06월 17일)

* SKOverlay 지원
* 전면/비디오 광고의 버튼 이미지 및 노출 위치 조정

### 1.6.7 (2025년 03월 25일)

* 전면 이미지 광고의 노출 영역 변경

### 1.6.6 (2025년 03월 05일)

* 비디오 광고 기능 개선

### 1.6.5 (2024년 09월 05일)

* 전면 이미지 및 배너 광고의 임프레션 이벤트 발생 위치 변경

### 1.6.4 (2024년 09월 04일)

* 전면 비디오 및 보상 광고의 임프레션 이벤트 발생 위치 변경

### 1.6.3 (2024년 08월 28일)

* SPM (Swift Package Manager)를 통한 SDK 설치 지원

### 1.6.2 (2024년 08월 26일)

* 전면 비디오 / 보상 광고 영상 재생 완료 후, 썸네일 이미지 처리관련 로직 수정

### 1.6.1 (2024년 07월 23일)

* 전면 비디오 / 보상 광고에 대한 재생 시간 보정

### 1.6.0 (2024년 02월 23일)

* PrivacyInfo.xcprivacy 파일 추가

### 1.5.9 (2024년 02월 15일)

* 보상광고의 rewardedAdDidEarnReward 이벤트 전달 타이밍 변경
* 전면 비디오 / 보상 광고 화면의 닫기 버튼에 대한 로직 변경
* 재생 가능한 비디오 컨텐츠인지 확인하는 로직 추가
* 네이티브 광고 관련 : removeMainImageAspectRatioConstraint 메소드 추가

### 1.5.8 (2023년 12월 12일)

* Apple SKAdNetwork 지원

### 1.5.7 (2023년 09월 01일)

* Xcode15 (베타 버전)에서 빌드 에러 발생 수정

### 1.5.6 (2023년 08월 16일)

* 비디오 광고의 Mute 버튼 아이콘 오류 수정

### 1.5.5 (2023년 08월 11일)

* 비디오 광고 URL의 유효성 확인 기능 추가

### 1.5.4 (2023년 08월 03일)

* 네이티브 광고 리소스 다운로드 크기 제한

### 1.5.3 (2023년 07월 31일)

* 네이티브 광고의 옵트아웃 뷰에 접근할 수 있도록 변경

### 1.5.2 (2023년 07월 27일)

* 비디오 광고 (보상, 전면) 타입 상관없이 CTA 버튼 및 SeekBar(Slider) 제거

### 1.5.1 (2023년 07월 24일)

* 보상 광고의 SeekBar(Slider) 제거
* 보상/전면 비디오 광고의 CTA 버튼 제거

### 1.5.0 (2023년 07월 04일)

* 전면 비디오 광고의 SeekBar(Slider) 제거

### 1.4.9 (2023년 05월 24일)

* 네이티브 광고 캐싱 과정에서의 응답 불가에 대한 예외 처리 수정
* SDK 안정화

### 1.4.8 (2023년 05월 12일)

* SDK 안정화

### 1.4.7 (2023년 04월 14일)

* 비디오 광고의 가로/세로 모드 구분 처리
* 전면 이미지 광고의 가로 모드 적용 (480x320)

### 1.4.6 (2023년 04월 04일)

* 리워드 비디오 광고 닫기 버튼 시간 보정

### 1.4.5 (2023년 03월 27일)

* 전면 광고와 리워드 비디오 광고의 닫기 버튼 변경
* SDK 안정화

### 1.4.4 (2023년 03월 16일)

* 전면 비디오 광고 추가

### 1.4.3 (2023년 03월 06일)

* 광고 트래픽을 HTTPS 통해서만 처리되도록 수정

### 1.4.2 (2023년 03월 03일)

* 확장 앱의 번들 정보 조회 변경

### 1.4.1 (2023년 02월 27일)

* SDK 안정화

### 1.4.0 (2023년 01월 31일)

* 라이브러리 타입 변경 (framework -> xcFramework)

### 1.3.9 (2023년 01월 26일)

* 버전 번호 변경, SDK 안정화
* 최소 지원 버전 변경 (8.0 -> 9.0)
* armv7 디바이스 미지원

### 1.3.8 (2023년 01월 02일)

* 버전 번호 변경

### 1.3.7 (2023년 01월 02일)

* 리워드 비디오 광고의 SSV(Server-Side-Verification) 기능 추가
* 리워드 비디오 광고의 safeAreaInsets 접근 방식 변경

### 1.3.6 (2022년 09월 20일)

* SDK 안정화

### 1.3.5 (2022년 09월 16일)

* 리워드 비디오 관련 개선

### 1.3.4 (2022년 06월 20일)

* 버그 수정

### 1.3.3 (2022년 06월 10일)

* 서버연동 관련 일부 수정

### 1.3.2 (2022년 03월 23일)

* 배너 클릭 오류 관련 수정

### 1.3.1 (2022년 01월 17일)

* 리워드 비디오 광고 관련 보완

### 1.3.0 (2022년 01월 17일)

* 리워드 비디오 광고 적용

### 1.2.10 (2021년 02월 09일)

* 프레임워크 지원 아키텍쳐 변경 (ARMV7 포함)

### 1.2.9 (2021년 02월 03일)

* 프레임워크 지원 아키텍쳐 변경 (ARMV7 제외)

### 1.2.8 (2020년 10월 07일)

* iOS 14 관련 대응 (XCode 12+)

### 1.2.7 (2020년 08월 25일)

* IDFV 수집
* 배너/전면 임프레션, 클릭 수집 관련 변경
* 광고 없음 (No Fill) 관련 에러 메시지 변경

### 1.2.6 (2019년 10월 24일)

* 배너 관련 성능 향상
* 전면광고의 프리젠테이션 스타일을 풀스크린으로 지정 (iOS 13)
* 샘플 프로젝트 다크모드 지원 (iOS 13)

### 1.2.5 (2019년 9월 25일)

* UIWebView 관련 제거

### 1.2.4 (2019년 8월 12일)

* 전면광고 X 버튼 위치 수정

### 1.2.3 (2019년 3월 28일)

* 모펍 미디에이션 지원을 위한 수정

### 1.2.2 (2018년 12월 27일)

* 타사 라이브러리간의 빌드 오류 관련 수정

### 1.2.1 (2018년 8월 24일)

* 전면광고 관련 보완

### 1.2.0 (2018년 7월 30일)

* 악성광고 관련 보완
* 최소 지원 OS 버전 변경 (Deployment Target : 6.0 -> 8.0)

### 1.1.9 (2017년 12월 5일)

* 네이티브 광고의 메인광고뷰(MainAdView) 관련 수정

### 1.1.8 (2017년 11월 16일)

* 네이티브 광고의 CTA(액션버튼) 관련 수정

### 1.1.7 (2017년 11월 14일)

* 네이티브 광고에 대한 이미지 캐싱 적용
* 네이티브 광고의 옵트아웃(opt-out) 적용
* 네이티브 광고에 대한 CTA(액션버튼) 적용

### 1.1.6 (2017년 11월 1일)

* 전면광고 종료 버튼 위치 조정

### 1.1.5 (2017년 6월 19일)

* 서버연동 관련 일부 수정

### 1.1.4 (2017년 2월 10일)

* 광고 요청의 제한시간 적용
* 에러코드 \[110] 추가 (광고 요청 제한시간)
* 광고 재요청 관련 수정

### 1.1.3 (2017년 1월 5일)

* 서버연동 관련 일부 수정
* 버그 수정

### 1.1.2 (2016년 12월 12일)

* iOS 10 에서 ATS 관련 대응
* 광고 웹뷰로 WKWebView 적용

### 1.1.1 (2016년 10월 26일)

* 네이티브 광고에 대한 예외처리 강화
* 네이티브 광고 표출을 위한 xib 파일의 수정

### 1.1.0 (2016년 10월 21일)

* 네이티브 광고 추가

### 1.0.5 (2016년 8월 30일)

* 배너 광고의 RootViewController 설정 추가 (Refresh 적용시 필수)

### 1.0.4 (2016년 8월 24일)

* 1.0.3 관련 보완

### 1.0.3 (2016년 8월 23일)

* 중복 오류 관련 일부 클래스의 이름 변경

### 1.0.2 (2016년 7월 8일)

* 배너 광고의 리프레쉬(Refresh) 관련 수정

### 1.0.1 (2016년 6월 21일)

* 배너 광고의 일부 오류 수정 (iframe)

### 1.0.0 (2016년 5월 27일)

* 초기 버전


# 프로젝트 설정

### SDK 연동을 위한 준비

#### Android

* Android Studio 환경
* Android 4.1 (API Version 16) 이상
* Android Support Library (android-support-v4.jar)

#### iOS

* Xcode 16.0 이상
* Deployment Target : iOS 12.0 이상

> 2025년 4월 24일부터 앱 스토어 커넥트에 업로드하는 앱은 Xcode 16 이상 버전을 사용하여 빌드해야 합니다.\
> \
> <https://developer.apple.com/kr/news/>

### Plugin 설치

[AdPie Flutter SDK](https://pub.dev/packages/adpie_sdk) 에서 릴리즈된 버전을 확인합니다.

#### 1. 터미널 명령어로 설치

```
$ flutter pub add adpie_sdk
```

#### 2. pubspec.yaml 에 dependency 입력

* 터미널 명령어로 설치한 경우 이 단계를 무시합니다.
* dependencies에 adpie\_sdk 를 추가합니다.

```yaml
dependencies:
  adpie_sdk: ^1.1.1
```

#### 3. AdPie SDK Dart 파일 임포트

```dart
import 'package:adpie_sdk/adpie_sdk.dart';
```


# 광고 연동

{% content-ref url="/pages/FIArL9bUNXMeiKnLN6i9" %}
[배너 광고](https://platform-business.gitbook.io/adpie/flutter/integration/banner)
{% endcontent-ref %}

{% content-ref url="/pages/f7lgW7w3SZtCsSTLSaGa" %}
[전면 광고](https://platform-business.gitbook.io/adpie/flutter/integration/interstitial)
{% endcontent-ref %}

{% content-ref url="/pages/n9amhu5IGsTf3RBimw9h" %}
[리워드 비디오 광고](https://platform-business.gitbook.io/adpie/flutter/integration/rewardedad)
{% endcontent-ref %}


# 배너 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/flutter/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : 광고 초기화

* 안드로이드의 경우 앱 실행 후 main() 에서 바로 초기화를 하는 것을 권장합니다.
* iOS의 경우 ATT(AppTrackingTransparency) 팝업 표출한 이후 초기화를 하는 것을 권장합니다.
* ATT(AppTrackingTransparency)는 [adpie\_sdk example](https://pub.dev/packages/adpie_sdk/example) 또는 [app\_tracking\_transparency](https://pub.dev/packages/app_tracking_transparency) 를 참고합니다.
* [사이트](http://my.adpies.com)에서 발급받은 Media ID를 `AdPieSdk.initialize()`에 넣어 호출합니다.

```dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isAndroid) {
    // AdPie SDK 초기화
    AdPieSdk.initialize(mediaId);
  } else {
    initPlugin();
  }

  runApp(const MyApp());
}

Future<void> initPlugin() async {
  final TrackingStatus status =
  await AppTrackingTransparency.trackingAuthorizationStatus;
  if (status == TrackingStatus.notDetermined) {
    final TrackingStatus status =
    await AppTrackingTransparency.requestTrackingAuthorization();
  }

  final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
  print("UUID: $uuid");

  // AdPie SDK 초기화
  AdPieSdk.initialize(mediaId);
}

```

### 3 : 광고 요청과 표출

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID와 배너 사이즈를 입력하여 호출합니다.
* 광고뷰가 사이트에서 설정한 슬롯 사이즈보다 작은 경우 요청하지 않거나 표출하지 않습니다.

```dart
@override
void initState() {
  super.initState();
  AdPieSdk.setAdViewListener(AdViewListener(
      onAdLoaded: (){
        // 광고 수신 성공
      },
      onAdFailedToLoad: (int errorCode) {
        // 광고 수신 실패
      },
      onAdClicked: (){
      
      }));

  AdPieSdk.setAdViewPosition(slotId, AdPieCommon.positionBottomCenter);
  AdPieSdk.loadAdView(slotId, AdPieCommon.size_320x50);
}

@override
void dispose() {
  super.dispose();

  AdPieSdk.destroyAdView(slotId);
}
```


# 전면 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/flutter/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : 광고 초기화

* 안드로이드의 경우 앱 실행 후 main() 에서 바로 초기화를 하는 것을 권장합니다.
* iOS의 경우 ATT(AppTrackingTransparency) 팝업 표출한 이후 초기화를 하는 것을 권장합니다.
* ATT(AppTrackingTransparency)는 [adpie\_sdk example](https://pub.dev/packages/adpie_sdk/example) 또는 [app\_tracking\_transparency](https://pub.dev/packages/app_tracking_transparency) 를 참고합니다.
* [사이트](http://my.adpies.com)에서 발급받은 Media ID를 `AdPieSdk.initialize()`에 넣어 호출합니다.

```dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isAndroid) {
    // AdPie SDK 초기화
    AdPieSdk.initialize(mediaId);
  } else {
    initPlugin();
  }

  runApp(const MyApp());
}

Future<void> initPlugin() async {
  final TrackingStatus status =
  await AppTrackingTransparency.trackingAuthorizationStatus;
  if (status == TrackingStatus.notDetermined) {
    final TrackingStatus status =
    await AppTrackingTransparency.requestTrackingAuthorization();
  }

  final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
  print("UUID: $uuid");

  // AdPie SDK 초기화
  AdPieSdk.initialize(mediaId);
}

```

### 3 : 광고 요청과 표출

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력하여 호출합니다.

```dart
@override
void initState() {
  super.initState();
  
  AdPieSdk.setInterstitialListener(InterstitialAdListener(
    onAdLoaded: (){
      // 광고 수신 성공
      bool isLoaded = (await AdPieSdk.isInterstitialLoaded(slotId))!;
      if (isLoaded) {
        // 광고 표출
        AdPieSdk.showInterstitial(slotId);
      }
    }, onAdFailedToLoad: (int errorCode){
      // 광고 수신 실패
    }, onAdFailedToShow: () {
      // 광고 표출 실패
    }, onAdShown: (){
    
    }, onAdClicked: (){
    
    }, onAdDismissed: (){
    
    })
  );

  // 광고 요청
  AdPieSdk.loadInterstitial(slotId);
}

@override
void dispose() {
  super.dispose();

  // 광고 해지
  AdPieSdk.destroyInterstitial(slotId);
}
```


# 리워드 비디오 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/flutter/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : 광고 초기화

* 안드로이드의 경우 앱 실행 후 main() 에서 바로 초기화를 하는 것을 권장합니다.
* iOS의 경우 ATT(AppTrackingTransparency) 팝업 표출한 이후 초기화를 하는 것을 권장합니다.
* ATT(AppTrackingTransparency)는 [adpie\_sdk example](https://pub.dev/packages/adpie_sdk/example) 또는 [app\_tracking\_transparency](https://pub.dev/packages/app_tracking_transparency) 를 참고합니다.
* [사이트](http://my.adpies.com)에서 발급받은 Media ID를 `AdPieSdk.initialize()`에 넣어 호출합니다.

```dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isAndroid) {
    // AdPie SDK 초기화
    AdPieSdk.initialize(mediaId);
  } else {
    initPlugin();
  }

  runApp(const MyApp());
}

Future<void> initPlugin() async {
  final TrackingStatus status =
  await AppTrackingTransparency.trackingAuthorizationStatus;
  if (status == TrackingStatus.notDetermined) {
    final TrackingStatus status =
    await AppTrackingTransparency.requestTrackingAuthorization();
  }

  final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
  print("UUID: $uuid");

  // AdPie SDK 초기화
  AdPieSdk.initialize(mediaId);
}

```

### 3 : 광고 요청과 표출

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력하여 호출합니다.

```dart
@override
void initState() {
  super.initState();
  
  AdPieSdk.setRewardedAdListener(RewardedAdListener(
    onAdLoaded: (){
      // 광고 수신 성공
      bool isLoaded = (await AdPieSdk.isRewardedAdLoaded(slotId))!;
      if (isLoaded) {
        // 광고 표출
        AdPieSdk.showRewardedAd(slotId);
      }
    }, onAdFailedToLoad: (int errorCode){
      // 광고 수신 실패
    }, onAdFailedToShow: () {
      // 광고 표출 실패
    }, onAdShown: (){
    
    }, onAdClicked: (){
    
    }, onAdRewarded: (){
      // 보상 수령
    }, onAdDismissed: (){
    
    }));

  AdPieSdk.loadRewardedAd(slotId);
}

@override
void dispose() {
  super.dispose();

  // 광고 해지
  AdPieSdk.destroyRewardedAd(slotId);
}
```


# 공통

{% content-ref url="/pages/j5niIbHJEAnFNXsVh2Q0" %}
[에러코드](https://platform-business.gitbook.io/adpie/flutter/common/errorcode)
{% endcontent-ref %}

{% content-ref url="/pages/CN88m36PBUxK597gopUv" %}
[변경내역](https://platform-business.gitbook.io/adpie/flutter/changelog)
{% endcontent-ref %}


# 에러코드

* SDK를 통한 광고 실패에 대한 코드와 메시지는 아래와 같이 정의되어 있습니다.

|  code | message                                           | description                                                       |
| :---: | ------------------------------------------------- | ----------------------------------------------------------------- |
| `100` | No fill.                                          | 광고 없음                                                             |
| `101` | Invalid ad request.                               | 잘못된 요청 파라미터 (Media ID, Slot ID, Bundle ID 확인)                     |
| `102` | A network error occurred.                         | 네트워크 오류 (서버통신 오류, 지속시 문의필요)                                       |
| `103` | No internet connection detected.                  | 연결된 인터넷 정보 없음 (인터넷 연결상태 확인)                                       |
| `104` | An internal error occurred.                       | 내부 오류 (발생시 문의필요)                                                  |
| `105` | AdPie SDK must be initialized before ads loading. | SDK 초기화 미완료 (연동 실패)                                               |
| `106` | Previous ad request is being processed.           | 중복 요청 (기존 요청이 끝나기전에 재요청)                                          |
| `107` | An error occurred while loading content.          | 컨텐츠 로딩 오류 (웹뷰의 컨텐츠 로딩실패)                                          |
| `108` | A server data error occurred.                     | 서버 데이터 오류 (데이터 파싱, 지속시 문의필요)                                      |
| `109` | Invalid ad layout.                                | 레이아웃 설정 오류 (배너의 경우 백그라운드 상태이거나 잘못된 슬롯 사이즈, 네이티브의 경우 필수 요소가 빠진 상태) |
| `110` | Ad request was blocked with minimum time limit.   | 광고 요청의 시간 제한 (기존 요청의 시간 비교 후 서버 전송 없음)                            |


# 샘플 애플리케이션

{% embed url="<https://github.com/gomfactory/AdPie-Flutter-SDK/tree/main/adpie_sdk>" %}


# 변경내역

### 1.1.1 (2026년 01월 27일)

* [Android SDK 1.16.2](https://platform-business.gitbook.io/pages/NX1eAUIFykBbXuITgjdJ#id-1.16.2-2026-01-06) 버전 적용
* [iOS SDK 1.6.15](https://platform-business.gitbook.io/pages/6P77j8trAuQ4uZwztnaB#id-1.6.15-2025-01-21) 버전 적용
* 전면, 리워드 비디오 광고에 "onAdFailedToShow" 이벤트 추가

### 1.1.0 (2026년 01월 08일)

* [Android SDK 1.15.1 ](https://platform-business.gitbook.io/pages/NX1eAUIFykBbXuITgjdJ#id-1.15.1-2025-11-05)버전 적용

### 1.0.4 (2025년 03월 25일)

* [iOS SDK 1.6.7](https://platform-business.gitbook.io/pages/6P77j8trAuQ4uZwztnaB#id-1.6.7-2025-03-25) 버전 적용

### 1.0.3 (2025년 03월 20일)

* [Android SDK 1.14.2](https://platform-business.gitbook.io/pages/NX1eAUIFykBbXuITgjdJ#id-1.14.2-2025-02-26) 버전 적용
* [iOS SDK 1.6.6](https://platform-business.gitbook.io/pages/6P77j8trAuQ4uZwztnaB#id-1.6.6-2025-03-05) 버전 적용

### 1.0.2 (2023년 12월 20일)

* Android SDK 1.13 이상 버전 적용
* iOS SDK 1.5 이상 버전 적용

### 1.0.1 (2023년 06월 30일)

* 광고 해지 관련 코드 보완

### 1.0.0 (2023년 06월 29일)

* 공식 버전 배포


# 프로젝트 설정

### SDK 연동을 위한 준비

* Unity 2019 이상
* Android
  * minSdkVersion 15 이상
* iOS
  * iOS 12.0 이상
  * Xcode 16.0 이상
  * CocoaPods

### SDK 설치

#### 1. SDK 다운로드 및 설치

* AdPie Unity Package [다운로드](https://github.com/gomfactory/AdPie-Unity-SDK/raw/master/AdPieUnity-1.1.2.unitypackage) 합니다.
* Unity 프로그램에서 `Assets > Import Package > Custom Package...` 을 통해 압축 해지하여 `AdPieUnity-x.x.x.unitypackage` 파일을 선택하여 Import를 진행합니다.

  <figure><img src="https://github.com/gomfactory/AdPie-Unity-SDK/wiki/image/unity_sample_screen_02.png" alt=""><figcaption></figcaption></figure>

#### 2. Android 프로젝트 설정

* Assets > External Dependency Manager > Android Resolver > Settings를 선택하고 `Use Jetifier` 체크 후 `Force Resolver` 를 실행합니다.\
  &#x20;

  <figure><img src="https://github.com/gomfactory/AdPie-Unity-SDK/wiki/image/unity_sample_screen_03.png" alt=""><figcaption></figcaption></figure>
* File > Build Settings > Platform에서 Android 선택 > Player Settings > Publishing Settings 로 이동한 다음, "`Custom Main Gradle Template`" 및 "`Custom Gradle Properties Template`" 체크합니다.

  <figure><img src="https://github.com/gomfactory/AdPie-Unity-SDK/wiki/image/unity_sample_screen_04.png" alt=""><figcaption></figcaption></figure>

#### 3. iOS 프로젝트 설정

* Xcode 14 이상부터, 비트코드를 사용한 빌드가 지원되지 않으므로, Build Settings의 각 빌드 타겟 (Unity-iPhone, UnityFramework)에서 비트코드 설정을 "No"로 변경합니다.

<figure><img src="https://github.com/gomfactory/AdPie-Unity-SDK/wiki/image/unity_sample_screen_05.png" alt=""><figcaption></figcaption></figure>

<figure><img src="https://github.com/gomfactory/AdPie-Unity-SDK/wiki/image/unity_sample_screen_06.png" alt=""><figcaption></figcaption></figure>


# 광고 연동

{% content-ref url="/pages/KizxfMdCVlVs7l886NA7" %}
[배너 광고](https://platform-business.gitbook.io/adpie/unity/integration/banner)
{% endcontent-ref %}

{% content-ref url="/pages/EQ573KJPMzPMSE8mjIqa" %}
[전면 광고](https://platform-business.gitbook.io/adpie/unity/integration/interstitial)
{% endcontent-ref %}

{% content-ref url="/pages/yOxd45Tp110AV5JXvKAi" %}
[리워드 비디오 광고](https://platform-business.gitbook.io/adpie/unity/integration/rewardedad)
{% endcontent-ref %}


# 배너 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/unity/project-settings)을 통해 광고 연동을 위한 준비를 합니다.

### 2 : SDK 초기화

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 합니다.

```csharp
AdPieSDK.Instance.Initialize("AdPie-Media-ID");
```

### 3 : 광고 요청과 표출

* [사이트](http://my.adpies.com)에서 발급받은 Slot ID를 입력하여 AdView 객체를 생성합니다.

```csharp
AdView adView = new AdView("AdPie-Slot-ID", AdView.POSITION_TOP, 320, 50);
adView.Load();
```

### 4 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* [에러코드](https://platform-business.gitbook.io/adpie/unity/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```csharp
{
    // 광고 연동을 위한 슬롯 ID를 필수로 입력한다.
    AdView adView = new AdView("AdPie-Slot-ID", AdView.POSITION_TOP, 320, 50);
    adView.OnAdLoaded += AdView_OnAdLoaded;
    adView.OnAdFailedToLoad += AdView_OnAdFailedToLoad;
    adView.OnAdClicked += AdView_OnAdClicked;
    adView.Load();
}

void AdView_OnAdLoaded()
{
    // 광고 표출 성공 후 이벤트 발생
}

void AdView_OnAdFailedToLoad(int errorCode)
{
    // 광고 요청 또는 표출 실패 후 이벤트 발생
}

void AdView_OnAdClicked()
{
    // 광고 클릭 후 이벤트 발생
}

```


# 전면 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/unity/project-settings)을 통해 광고 연동을 위한 준비를 합니다.
* [사이트](http://my.adpies.com) 에서 매체를 등록하여 Media ID 를 발급받고, 슬롯을 등록하면서 광고 유형을 비디오 또는 이미지 광고를 선택하고 Slot ID 를 발급받습니다.

### 2 : SDK 초기화

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 합니다.

```csharp
AdPieSDK.Instance.Initialize("AdPie-Media-ID");
```

### 3 : 광고 요청과 표출

* 사이트에서 발급받은 Slot ID를 입력하여 InterstitialAd 객체를 생성합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있습니다.
* 광고 요청시 Load() 메소드를 호출하고, 표출 시 Show()를 호출을 합니다.
* 광고 컨텐츠가 로드되지 않을 가능성이 있기에 IsLoaded()를 통해 확인 후 Show() 메소드를 호출합니다.

```csharp
{
    // 광고 연동을 위한 슬롯 ID를 필수로 입력합니다.
    InterstitialAd interstitialAd = new InterstitialAd("AdPie-Slot-ID");
    interstitialAd.Load();
}
```

### 4 : 광고 리스너 사용

* 전면 (이미지, 비디오) 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* [에러코드](https://platform-business.gitbook.io/adpie/unity/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```csharp
{
    InterstitialAd interstitialAd = new InterstitialAd("AdPie-Slot-ID");
    interstitialAd.OnAdLoaded += InterstitialAd_OnAdLoaded;
    interstitialAd.OnAdFailedToLoad += InterstitialAd_OnAdFailedToLoad;
    interstitialAd.OnAdClicked += InterstitialAd_OnAdClicked;
    interstitialAd.OnAdShown += InterstitialAd_OnAdShown;
    interstitialAd.OnAdDismissed += InterstitialAd_OnAdDismissed;
    interstitialAd.Load();
}

void InterstitialAd_OnAdLoaded()
{
    // 광고 로딩 완료 후 이벤트 발생
    
    // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
    if (interstitialAd != null && interstitialAd.IsLoaded())
    {
        interstitialAd.Show();
    }
    
}

void InterstitialAd_OnAdFailedToLoad(int errorCode)
{
    // 광고 요청 또는 표출 실패 후 이벤트 발생
}

void InterstitialAd_OnAdClicked()
{
    // 광고 클릭 후 이벤트 발생
}

void InterstitialAd_OnAdShown()
{
    // 광고 표출 후 이벤트 발생
}

void InterstitialAd_OnAdDismissed()
{
    // 광고가 표출한 뒤 사라질 때 이벤트 발생
}
```

* 비디오 광고의 경우 비디오 플레이에 대한 이벤트를 받을 수 있습니다.

```csharp
{
    // optional
    VideoAdPlaybackListener videoAdPlaybackListener = new VideoAdPlaybackListener();
    videoAdPlaybackListener.OnVideoAdStarted += OnVideoAdStarted;
    videoAdPlaybackListener.OnVideoAdPaused += OnVideoAdPaused;
    videoAdPlaybackListener.OnVideoAdStopped += OnVideoAdStopped;
    videoAdPlaybackListener.OnVideoAdSkipped += OnVideoAdSkipped;
    videoAdPlaybackListener.OnVideoAdError += OnVideoAdError;
    videoAdPlaybackListener.OnVideoAdCompleted += OnVideoAdCompleted;
    interstitialAd.setVideoAdPlaybackListener(videoAdPlaybackListener);
}

void OnVideoAdStarted()
{
    // 비디오 광고 시작 이벤트 알림
}

void OnVideoAdPaused()
{
    // 비디오 광고 일시중지 이벤트 알림
}

void OnVideoAdStopped()
{
    // 비디오 광고 중지 이벤트 알림
}

void OnVideoAdSkipped()
{
    // 비디오 광고 건너뜀 이벤트 알림
}

void OnVideoAdError()
{
    // 비디오 광고 오류 이벤트 알림
}

void OnVideoAdCompleted()
{
    // 비디오 광고 완료 이벤트 알림
}

```


# 리워드 비디오 광고

### 1 : 준비

* [프로젝트 설정](https://platform-business.gitbook.io/adpie/unity/project-settings)을 통해 광고 연동을 위한 준비를 합니다.
* [사이트](http://my.adpies.com) 에서 매체를 등록하여 Media ID와 Slot ID 를 발급받습니다.

### 2 : SDK 초기화

* SDK 초기화를 하지 않았다면, [사이트](http://my.adpies.com)에서 발급받은 Media ID를 입력하여 초기화를 합니다.

```csharp
AdPieSDK.Instance.Initialize("AdPie-Media-ID");
```

### 3 : 광고 요청과 표출

* 사이트에서 발급받은 Slot ID를 입력하여 RewardedVideoAd 객체를 생성합니다.
* 광고 요청과 표출로 메소드가 각각 나누어져 있습니다.
* 광고 요청시 Load() 메소드를 호출하고, 표출 시 Show()를 호출을 합니다.
* 광고 컨텐츠가 로드되지 않을 가능성이 있기에 IsLoaded()를 통해 확인 후 Show() 메소드를 호출합니다.

```csharp
{
    // 광고 연동을 위한 슬롯 ID를 필수로 입력한다.
    RewardedVideoAd rewardedVideoAd = new RewardedVideoAd("AdPie-Slot-ID");
    rewardedVideoAd.Load();
}
```

### 4 : 광고 리스너 사용

* 광고 요청에 대한 이벤트를 수신할 수 있습니다.
* [에러코드](https://platform-business.gitbook.io/adpie/unity/common/errorcode)를 통해 광고 실패에 대한 이유를 알 수 있습니다.

```csharp
{
    RewardedVideoAd rewardedVideoAd = new RewardedVideoAd("AdPie-Slot-ID");
    rewardedVideoAd.OnRewardedVideoLoaded += RewardedVideoAd_OnRewardedVideoLoaded;
    rewardedVideoAd.OnRewardedVideoFailedToLoad += RewardedVideoAd_OnRewardedVideoFailedToLoad;
    rewardedVideoAd.OnRewardedVideoClicked += RewardedVideoAd_OnRewardedVideoClicked;
    rewardedVideoAd.OnRewardedVideoStarted += RewardedVideoAd_OnRewardedVideoStarted;
    rewardedVideoAd.OnRewardedVideoFinished += RewardedVideoAd_OnRewardedVideoFinished;
    rewardedVideoAd.Load();
}

void RewardedVideoAd_OnRewardedVideoLoaded()
{
    // 광고 로딩 완료 후 이벤트 발생
    
    // 광고 요청 후 즉시 노출하고자 할 경우 아래의 코드를 추가합니다.
    if (rewardedVideoAd != null && rewardedVideoAd.IsLoaded())
    {
        rewardedVideoAd.Show();
    }
    
}

void RewardedVideoAd_OnRewardedVideoFailedToLoad(int errorCode)
{
    // 광고 요청 또는 표출 실패 후 이벤트 발생
}

void RewardedVideoAd_OnRewardedVideoClicked()
{
    // 광고 클릭 후 이벤트 발생
}

void RewardedVideoAd_OnRewardedVideoStarted()
{
    // 리워드 동영상 광고 시작 이벤트 발생
}

void RewardedVideoAd_OnRewardedVideoFinished(int finishState)
{
    // 리워드 동영상 광고 종료 이벤트 발생
    string state = "";
    switch(finishState) {
        case 0:
            state = "UNKNOWN";
            break;
        case 1:
            // 동영상 광고 시청완료
            state = "COMPLETED";
            break;
        case 2:
            // 동영상 광고 오류
            state = "ERROR";
            break;
        case 3:
            // 동영상 광고 건너뜀
            state = "SKIPPED";
            break;
    }
}
```


# 공통


# 에러코드

* SDK를 통한 광고 실패에 대한 코드와 메시지는 아래와 같이 정의되어 있습니다.

|  code | message                                                                | description                                                       |
| :---: | ---------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `100` | Ad request successful, but no ad returned due to lack of ad inventory. | 광고 없음                                                             |
| `101` | Invalid ad request.                                                    | 잘못된 요청 파라미터 (Media ID, Slot ID, Package Name 또는 Bundle ID 확인)     |
| `102` | A network error occurred.                                              | 네트워크 오류 (서버통신 오류, 지속시 문의필요)                                       |
| `103` | No internet connection detected.                                       | 연결된 인터넷 정보 없음 (인터넷 연결상태 확인)                                       |
| `104` | An internal error occurred.                                            | 내부 오류 (발생시 문의필요)                                                  |
| `105` | AdPie SDK must be initialized before ads loading.                      | SDK 초기화 미완료 (연동 실패)                                               |
| `106` | Previous ad request is being processed.                                | 중복 요청 (기존 요청이 끝나기전에 재요청)                                          |
| `107` | An error occurred while loading content.                               | 컨텐츠 로딩 오류 (웹뷰의 컨텐츠 로딩실패)                                          |
| `108` | A server data error occurred.                                          | 서버 데이터 오류 (데이터 파싱, 지속시 문의필요)                                      |
| `109` | Invalid ad layout.                                                     | 레이아웃 설정 오류 (배너의 경우 백그라운드 상태이거나 잘못된 슬롯 사이즈, 네이티브의 경우 필수 요소가 빠진 상태) |
| `110` | Ad request was blocked with minimum time limit.                        | 광고 요청의 시간 제한 (기존 요청의 시간 비교 후 서버 전송 없음)                            |


# 샘플 애플리케이션

{% embed url="<https://github.com/gomfactory/AdPie-Unity-SDK/tree/master/AdPieSample>" %}


# 변경내역

### 1.1.2 (2024년 9월 24일)

* Android SDK 1.13.7 연동
* iOS SDK 1.6.5 연동
* EDM4U(External Dependency Manager for Unity) 1.2.179 업데이트

### 1.1.1 (2024년 4월 5일)

* Android SDK 1.13.4 연동
* iOS SDK 1.6.0 연동

### 1.1.0 (2023년 2월 2일)

* Android SDK 1.10.1 연동
* iOS SDK 1.4.0 연동

### 1.0.9 (2022년 6월 21일)

* Android SDK 1.9.5 연동
* iOS SDK 1.3.4 연동

### 1.0.8 (2022년 4월 19일)

* Android IL2CPP 방식의 빌드 오류 수정

### 1.0.7 (2022년 3월 23일)

* iOS SDK 1.3.2 연동

### 1.0.6 (2022년 2월 21일)

* Android SDK 1.9.4 연동

### 1.0.5 (2022년 1월 17일)

* iOS SDK 1.3.1 연동

### 1.0.4 (2022년 1월 10일)

* Android SDK 1.9.3 연동
* iOS SDK 1.2.10 연동

### 1.0.3 (2020년 9월 8일)

* Android SDK 1.8.1 연동
* iOS SDK 1.2.7 연동

### 1.0.2 (2019년 10월 2일)

* Android SDK 1.7.2 연동
* iOS SDK 1.2.5 연동

### 1.0.1 (2019년 8월 29일)

* Android SDK 1.6.7 연동
* iOS SDK 1.2.4 연동

### 1.0.0 (2018년 10월 23일)

* 초기 버전


# For Buyers

## Introduction

ADPIE-Exchange is platform to simplify integration of Demand Side Platform(DSP) with Sell Side Platform(SSP). This document defines the protocol for interaction between DSP and ADPIE-exchange.

## Integration Spec

Basically support OpenRTB 2.3 and OpenRTB Native-Ads-Specification 1.1, including scalability use extension field. Addition/deletion of field is available according to application.

&#x20;    •        HTTP 1.1 based POST method

&#x20;    •        Data Format: JSON

&#x20;    •        Not support Multiple impression per one request

&#x20;    •        Support some parts of OpenRTB 2.5 and OpenRTB Native-Ads-specification 1.2.

&#x20;    •        Supported Ad Formats: Banner, Native, Rewarded video

&#x20;    •        Supported Size: 320x50, 320x100, 320x480, 300x250, 1200x627, 1280x720, 720x1280

## Bid Request

### Bid Request Object<br>

<table><thead><tr><th width="119.75390625" valign="top">Field</th><th width="149.9296875" valign="top">Type</th><th width="89.109375" valign="top">Required</th><th width="249.765625" valign="top">Description</th><th valign="top">Example</th></tr></thead><tbody><tr><td valign="top">id</td><td valign="top">string</td><td valign="top">O</td><td valign="top">unique ID of the bid request</td><td valign="top">“bb046a99 f84dad1fa 7ac3b0ce4 bc4dd3”</td></tr><tr><td valign="top">imp</td><td valign="top">array of objects</td><td valign="top">O</td><td valign="top"><p>impression object</p><p>The current version supports only 1 Imp object.</p></td><td valign="top"> </td></tr><tr><td valign="top">app</td><td valign="top">object</td><td valign="top"> O</td><td valign="top"><p>app object(i.e., non-browser applications). Only applicable and recommended for apps.</p><p>Either site or app object should be present.</p></td><td valign="top"> </td></tr><tr><td valign="top">site</td><td valign="top">object</td><td valign="top"> O</td><td valign="top"><p>site object.</p><p>Only applicable and recommended for websites.</p><p>Either site or app object should be present.</p></td><td valign="top"> </td></tr><tr><td valign="top">device</td><td valign="top">object</td><td valign="top">O</td><td valign="top">Device Object which describes the device the impression will be delivered to.</td><td valign="top"> </td></tr><tr><td valign="top">user</td><td valign="top">object</td><td valign="top">O</td><td valign="top">User Object which describes the user.</td><td valign="top"> </td></tr><tr><td valign="top">tmax</td><td valign="top">integer</td><td valign="top"></td><td valign="top">Maximum time in milliseconds to submit a bid to avoid timeout.(milliseconds)</td><td valign="top">400</td></tr><tr><td valign="top">cur</td><td valign="top">array of strings</td><td valign="top"></td><td valign="top">Array of allowed currencies for bids on this bid request.</td><td valign="top">[“USD”]</td></tr><tr><td valign="top">bcat</td><td valign="top">array of strings</td><td valign="top"></td><td valign="top">Blocked Advertiser Categories. (Refer to 5.4 Content Categories)</td><td valign="top">["IAB7","IAB26","IAB25-3","IAB7-17 "]</td></tr><tr><td valign="top">badv</td><td valign="top">array of strings</td><td valign="top"></td><td valign="top"></td><td valign="top">[“block1.com”,“block2.com”]</td></tr><tr><td valign="top">at</td><td valign="top">integer</td><td valign="top"></td><td valign="top">Auction type, where 1=First Price, 2=Second Price Plus.</td><td valign="top">2</td></tr><tr><td valign="top">ext</td><td valign="top">object</td><td valign="top"></td><td valign="top">Impression ext object for exchange-specific extensions to OpenRTB.</td><td valign="top"></td></tr></tbody></table>

### &#x20;Impression Object

<table><thead><tr><th width="119.63671875" valign="top">Field</th><th width="149.9375" valign="top">Type</th><th width="89.1015625" valign="top">Required</th><th width="250.20703125" valign="top">Description</th><th valign="top">Example</th></tr></thead><tbody><tr><td valign="top">id</td><td valign="top">string</td><td valign="top">O</td><td valign="top">impression ID within the bid request.</td><td valign="top">“1”</td></tr><tr><td valign="top">banner</td><td valign="top">object</td><td valign="top"> </td><td valign="top">Banner object. Required for banner impressions.</td><td valign="top"> </td></tr><tr><td valign="top">native</td><td valign="top">object</td><td valign="top"> </td><td valign="top"><a href="https://protocol.bidswitch.com/standards/native.html#native">Native Object</a> describes the ad properties. Required for native impressions.</td><td valign="top"> </td></tr><tr><td valign="top">bidfloor</td><td valign="top">float</td><td valign="top"> </td><td valign="top">Bid floor as set by the SSP. The currency is the same as specified in cur field.</td><td valign="top">0.01080</td></tr><tr><td valign="top">bidfloorcur</td><td valign="top">string</td><td valign="top"> </td><td valign="top">Bid floor currency specified using ISO-4217 alpha codes.</td><td valign="top">“USD”</td></tr><tr><td valign="top">secure</td><td valign="top">integer</td><td valign="top"> </td><td valign="top">0 for non-secure pages (default); 1 for secure pages. Creatives for secure pages should be SSL-compliant.</td><td valign="top">0</td></tr><tr><td valign="top">instl</td><td valign="top">integer</td><td valign="top"> </td><td valign="top">1 if the ad is interstitial or full screen; else 0 (i.e., no).</td><td valign="top">1</td></tr><tr><td valign="top">pmp</td><td valign="top">object</td><td valign="top"> </td><td valign="top">Private Marketplace object</td><td valign="top"> </td></tr><tr><td valign="top">tagid</td><td valign="top">string</td><td valign="top"> </td><td valign="top">Identifier for specific ad placement or ad tag that was used to initiate the auction. This can be useful for debugging of any issues, or for optimization by the buyer.</td><td valign="top"> </td></tr><tr><td valign="top">displayman ager</td><td valign="top">string</td><td valign="top"> </td><td valign="top">Name of ad mediation partner, SDK technology, or player responsible for rendering ad (typically video or mobile).</td><td valign="top">“adpiessdk”</td></tr><tr><td valign="top">displayman agerver</td><td valign="top">string</td><td valign="top"></td><td valign="top">Version of ad mediation partner, SDK technology, or player responsible for rendering ad (typically video or mobile).</td><td valign="top">"011402"</td></tr></tbody></table>

### Banner Object

<table><thead><tr><th width="119.84765625">Field</th><th width="150.42578125">Type</th><th width="89.58984375">Required</th><th width="249.9765625">Description</th><th>Example</th></tr></thead><tbody><tr><td>id</td><td>string</td><td></td><td>Unique identifier for this banner object. Used for tracking multiple banner objects.</td><td>"1"</td></tr><tr><td>w</td><td>integer</td><td>O</td><td>Width of the impression in pixels.</td><td>320</td></tr><tr><td>h</td><td>integer</td><td>O</td><td>Height of the impression in pixels.</td><td>50</td></tr><tr><td>btype</td><td>array of integers</td><td></td><td>Blocked creative types. See Table 5.5 Banner Ad Types. If blank, assume all types are allowed.</td><td>[1,3]</td></tr><tr><td>battr</td><td><p>array of</p><p>integers</p></td><td></td><td>Blocked creative attributes. See Table 5.7</td><td>[1,4]</td></tr></tbody></table>

### Video Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>mimes</td><td>array of integers</td><td>O</td><td>Content MIME types supported</td><td>[“video/mp4”]</td></tr><tr><td>w</td><td>integer</td><td>O</td><td>Width of the video player in device independent pixels</td><td>320</td></tr><tr><td>h</td><td>integer</td><td>O</td><td>Height of the video player in device independent pixels</td><td>50</td></tr><tr><td>minduration</td><td>integer</td><td>O</td><td>Minimum video ad duration in seconds</td><td>5</td></tr><tr><td>maxduration</td><td>integer</td><td>O</td><td>Maximum video ad duration in seconds</td><td>30</td></tr><tr><td>protocols</td><td>array of integers</td><td>O</td><td>Array of supported video protocols. Refer to List 5.13.</td><td>[1,2,3]</td></tr><tr><td>startdelay</td><td>integer</td><td></td><td>Indicates the start delay in seconds for pre-roll, mid-roll, or post-roll ad placements. Refer to List 5.14 for additional generic values.</td><td>0</td></tr><tr><td>linearity</td><td>integer</td><td></td><td>Indicates if the impression must be linear, nonlinear, etc. If none specified, assume all are allowed. Refer to List 5.15</td><td>1</td></tr><tr><td>skip</td><td>integer</td><td></td><td>Indicates if the player will allow the video to be skipped, where 0 = no, 1 = yes.</td><td>1</td></tr><tr><td>skipmin</td><td>integer</td><td></td><td>Videos of total duration greater than this number of seconds can be skippable; only applicable if the ad is skippable.</td><td>3</td></tr><tr><td>skipafter</td><td>integer</td><td></td><td>Number of seconds a video must play before skipping is enabled; only applicable if the ad is skippable.</td><td>5</td></tr><tr><td>battr</td><td>array of integers</td><td></td><td><p>Blocked creative attributes.</p><p>See Table 5.7.</p></td><td>[1,3]</td></tr><tr><td>boxingallowed</td><td>integer</td><td></td><td>Indicates if letter-boxing of 4:3 content into a 16:9 window is allowed, where 0 = no, 1 = yes.</td><td>1</td></tr><tr><td>delivery</td><td>array of integers</td><td></td><td>Supported delivery methods. If none specified, assume all are supported. Refer to List 5.17.</td><td>[1,2]</td></tr><tr><td>api</td><td>array of integers</td><td></td><td>List of supported API frameworks for this impression. Refer to List 5.18. If an API is not explicitly listed, it is assumed not to be supported.</td><td>[1,3]</td></tr></tbody></table>

### Native Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>request</td><td>string</td><td>O</td><td>Request payload complying with the Native Ad Specification.</td><td></td></tr><tr><td>ver</td><td>string</td><td></td><td>Version of the Native Ad Specification to which request complies.</td><td>"1.1"</td></tr><tr><td>battr</td><td>array of integers</td><td></td><td>Blocked creative attributes. See Table 5.7</td><td>[1,3]</td></tr></tbody></table>

### Native Request Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>assets</td><td>string</td><td>O</td><td>Request payload complying with the Native Ad Specification.</td><td></td></tr><tr><td>ver</td><td>string</td><td></td><td>Version of the Native Ad Specification to which request complies.</td><td>"1.1"</td></tr><tr><td>battr</td><td>array of integers</td><td></td><td>Blocked creative attributes. See Table 5.7</td><td>[1,3]</td></tr></tbody></table>

### Native Asset Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>id</td><td>integer</td><td>O</td><td>Unique asset ID, assigned by exchange</td><td>1</td></tr><tr><td>required</td><td>integer</td><td></td><td>Set to 1 if asset is required (exchange will not accept a bid without it)</td><td>0</td></tr><tr><td>title</td><td>object</td><td></td><td>Native title object, see the <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-title-obj">Native Asset Title</a> <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-title-obj">Object</a> for more details.</td><td></td></tr><tr><td>img</td><td>object</td><td></td><td>Native image object, see the <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-image-obj">Native Asset</a> <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-image-obj">Image Object</a> for more details.</td><td></td></tr><tr><td>data</td><td>object</td><td></td><td>Native asset data object, see the <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-data-obj">Native</a> <a href="https://protocol.bidswitch.com/standards/native-request.html#native-assets-data-obj">Asset Data Object</a> section for more details.</td><td></td></tr></tbody></table>

### Native Asset Title Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>len</td><td>integer</td><td>O</td><td>Maximum length of the text in the title element.</td><td>25</td></tr></tbody></table>

### Native Asset Image Object

<table><thead><tr><th width="118.94921875">Field</th><th width="150.42578125">Type</th><th width="90.27734375">Required</th><th width="249.40234375">Description</th><th>Example</th></tr></thead><tbody><tr><td>type</td><td>integer</td><td>O</td><td><p>Type ID of the image element</p><p>supported by the publisher. Reter to 5.9</p></td><td>3</td></tr><tr><td>w</td><td>integer</td><td></td><td>Width of the image in pixels</td><td>1200</td></tr><tr><td>h</td><td>integer</td><td></td><td>Height of the image in pixels</td><td>627</td></tr></tbody></table>


