# iOS용 네이티브 광고 통합

> 네이티브 광고 오브젝트 생성하고 로드하고, 델리게이트를 구현하고, 뷰를 디자인하고, 광고 콘텐츠 바인딩하여 네이티브 광고를 통합할 수 있습니다.

네이티브 광고는 앱의 다른 콘텐츠 블렌딩 커스터마이즈 수 있는 광고 형태입니다. 이렇게 하면 광고가 더 자연스럽게 표시되므로 사용자 경험 리텐션 향상됩니다.

## 필수 조건##prerequisites

레벨플레이 SDK 8.4.0 이상을 애플리케이션 올바르게 연동했는지 확인합니다. 통합은 [여기](/grow/levelplay/sdk/ios/sdk-integration.md) 설명되어 있습니다.

## 네이티브 광고 통합##integrate-native-ads

네이티브 광고를 연동하려면 다음 5단계를 따르십시오. 

1. 네이티브 광고 오브젝트 생성 및 로드
2. 델리게이트 구현
3. 뷰 디자인 및 바인드
4. 네이티브 광고 표시
5. 네이티브 광고 제거

**단계 1. 네이티브 광고 오브젝트** 생성 및 로드

1. 오브젝트 커스텀 설정 허용하는 LevelPlayNativeAdBuilder 클래스 사용하여 네이티브 광고 오브젝트 생성합니다. 별도의 클래스 만들어 네이티브 광고 로딩 메커니즘을 한 곳에서 관리하는 것이 좋습니다.

   ```objective-c
   LevelPlayNativeAd *levelPlayNativeAd = [[[[LevelPlayNativeAdBuilder new] 
   withViewController:self] 
   withPlacementName:YOUR_PLACEMENT_NAME] // 플레이스먼트로 대체하거나 비워 둡니다.
   withDelegate:self]	// We implement the delegate in step 2
   .build;
   ```

   ```objective-c
   let levelPlayNativeAd: LevelPlayNativeAd = LevelPlayNativeAdBuilder()
               .withViewController(self)
               .withPlacementName(YOUR_PLACEMENT_NAME) // 플레이스먼트로 교체하거나 비워 둡니다.
               .withDelegate(self)
               .build()

   ```

   로딩 프로세스에 시간이 많이 소요될 수 있으므로 사용자에게 노출하기 직전에 네이티브 광고를 생성해야 합니다. 유효성 변경 가능성이 낮기 때문에 짧은 시간 내에 연속 요청을 하는 것이 좋지 않습니다.
2. 광고 오브젝트를 빌드한 후 네이티브 광고를 로드하고 **NativeAdView** 유형의 새 뷰를 만듭니다. 광고가 델리게이트의 **didLoad** 콜백을 통해 로드되면 알림이 표시됩니다.\*\*

   ```objective-c
   [levelPlayNativeAd loadAd];
   NativeAdView *levelPlayNativeAdView = [[NativeAdView alloc] init];
   ```

   ```objective-c
   levelPlayNativeAd.load()
   let levelPlayNativeAdView = NativeAdView()
   ```

   네이티브 광고와 해당 조회에 대한 레퍼런스를 유지하는 것이 좋습니다. 이 레퍼런스는 didLoad 콜백 트리거된 후 뷰를 채우는 데 사용됩니다.

   ```objective-c
   @property (비핵화, 강력함) LevelPlayNativeAd *nativeAd;
   @properties (nonatomic, strong) NativeAdView *nativeAdView; // 3단계에서 NativeAdView를 정의합니다.
   ```

   ```objective-c
   private var nativeAd: LevelPlayNativeAd!
   private var nativeAdView: NativeAdView! // 3단계에서 NativeAdView를 정의합니다.
   ```

   광고가 로드되고 뷰가 초기화된 후 이러한 레퍼런스를 유지해야 합니다.

   ```objective-c
      _nativeAd = levelPlayNativeAd;
      _nativeAdView = levelPlayNativeAdView;
   ```

   ```objective-c
     nativeAd = levelPlayNativeAd    
     nativeAdView = levelPlayNativeAdView
   ```

## 2단계. 델리게이트 구현##step-2.-implement-the-delegate

코드에 **LevelPlayNativeAdDelegate를 구현**합니다. 레벨플레이 SDK는 네이티브 광고 활동을 알려주는 여러 콜백을 작동시킵니다. SDK는 아래에 나열된 모든 이벤트를 리스너에게 알립니다.

```objective-c
// LevelPlayNativeAdDelegate
/**
 네이티브 광고가 성공적으로 로드된 후 호출됨
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */
-(void)didLoad:(LevelPlayNativeAd *)nativeAd
    withAdInfo:(ISAdInfo *)adInfo{}
/**
 네이티브가 광고를 로드하려고 시도했지만 실패한 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param error 오류의 원인
 */
-(void)didFailToLoad:(LevelPlayNativeAd *)nativeAd
           withError:(NSError *) 오류;{}
/**
 네이티브 광고 노출이 기록된 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */
-(void)didRecordImpression:(LevelPlayNativeAd *)nativeAd
                withAdInfo:(ISAdInfo *)adInfo{}
/**
 네이티브 광고가 클릭된 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */
-(void)didClick:(LevelPlayNativeAd *)nativeAd
     withAdInfo:(ISAdInfo *)adInfo;{}
```

```objective-c
// LevelPlayNativeAdDelegate
/**
 네이티브 광고가 성공적으로 로드된 후 호출됨
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */ 
func didLoad(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {}
/**
 네이티브가 광고를 로드하려고 시도했지만 실패한 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param error 오류의 원인
 */    
func didFail(_ nativeAd: LevelPlayNativeAd, withError 오류: 오류) {}
 
/**
 네이티브 광고 노출이 기록된 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */   
func didRecordImpression(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {}
   
/**
 네이티브 광고가 클릭된 후 호출됩니다.
 @param nativeAd Level Play 네이티브 광고입니다.
 @param adInfo 광고 정보입니다.
 */ 
func didClick(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {}
```

> **Note:**
>
> 로딩을 위해 생성된 네이티브 광고 오브젝트 콜백에 반환된 오브젝트 동일한 네이티브 광고 오브젝트 참조합니다.

## 3단계. 네이티브 광고 보기 디자인 및 바인드##step-3.-design-a-native-ad-view-and-bind-it

네이티브 광고를 로드하기 전에 새 뷰를 생성하고 바인드 모든 관련 정보를 수동으로 설정해야 합니다. 여기에는 아래와 같이 다양한 에셋을 정렬하는 것이 포함됩니다.

1. 다음 뷰([.xib](https://developers.is.com/wp-content/uploads/2024/03/ISNativeAdView.xib)) 파일을 프로젝트에 다운로드하여 임포트하고 프로젝트의 대상에 추가합니다. 파일에는 네이티브 광고 에셋을 보관할 뷰가 포함되어 있습니다. 인터페이스 빌더를 사용하여 앱 디자인에 따라 컴포넌트를 커스터마이즈. .xib 파일을 수정하는 동안 사전 정의된 아울렛에서 컴포넌트의 연결을 해제하지 마십시오. 이 디자인에는 다음과 같은 컴포넌트가 포함되어 있습니다.
   * 보기 #1: adAppIcon(UIImageView)
   * 보기 2: adTitleView(UILabel)
   * 보기 #3: adAdvertiserView(UILabel)
   * 보기 4: adBodyView(UILabel)
   * 보기 #5: adMediaView(커스텀 클래스 **LevelPlayMediaView**가 있는 UIView) 
   * 보기 #6: adCallToActionView(UIButton)
2. 뷰를 나타내는 커스텀 클래스를 생성하여 **UIView에서** 상속합니다.

   ```objective-c
   #import <IronSource/IronSource.h>
   @interface NativeAdView : UIView
   @properties (nonatomic, strong) ISNativeAdView *nativeAdView;
   - (void)populateWithContent:(nonnull LevelPlayNativeAd *)nativeAd;
   @end
   @implementation NativeAdView
   - (인스턴스 타입)init {
       UINib *nib = [UINib nibWithNibName:@"ISNativeAdView" bundle:[NSBundle mainBundle]];
       
       NSArray *nibContents = [nib instantiateWithOwner:nil options:nil];
       self.nativeAdView = (NativeAdView *)[nibContents firstObject];
       self.translatesAutoresizingMaskIntoConstraints = NO;
       self.nativeAdView.translatesAutoresizingMaskIntoConstraints = NO;
       
       // adding your own ad badge, privacy icon, or delete button here
     // ...
       return self;
   }
   // This function will be useful when the didLoad call back arrives
   - (void)populateWithContent:(nonnull LevelPlayNativeAd *)nativeAd {
       // Assigning views contents to the nativeAdView
       if (nativeAd.icon.image) {
           self.nativeAdView.adAppIcon.image = nativeAd.icon.image;
       } else {
           [self.nativeAdView.adAppIcon removeFromSuperview];
       }
       if (nativeAd.title) {
           self.nativeAdView.adTitleView.text = nativeAd.title;
       }
       if (nativeAd.advertiser) {
           self.nativeAdView.adAdvertiserView.text = nativeAd.advertiser;
       }
       if (nativeAd.body) {
           self.nativeAdView.adBodyView.text = nativeAd.body;
       }
       if (nativeAd.callToAction) {
           [self.nativeAdView.adCallToActionView setTitle:nativeAd.callToAction forState:UIControlStateNormal];
       // To ensure proper processing of touch events by the SDK, user interaction should be disabled
           self.nativeAdView.adCallToActionView.userInteractionEnabled = NO;
       }
       // call function to register native ad
       [self.nativeAdView registerNativeAdViews:nativeAd];
   }
   @end
   ```

   ```objective-c
   임포트 UIKit
   임포트 Ironsource
   class NativeAdView: UIView {
       private var nativeAdView: ISNativeAdView!
       
       오버라이드 init(프레임: CGRect) {
           super.init(frame: frame)
           let nib = UINib(nibName: "ISNativeAdView", bundle: .main)
           
           let nibContents = nib.instantiate(withOwner: nil, options: nil)
           self.nativeAdView = nibContents.first as? ISNativeAdView ?? ISNativeAdView()
           
           self.translatesAutoresizingMaskIntoConstraints = false
           self.nativeAdView?.translatesAutoresizingMaskIntoConstraints = false
           
           // adding your own ad badge, privacy icon, or delete button here
           // ...
           addSubview(nativeAdView)
       }
       
       필수 init?(coder: NSCoder) {
           super.init(coder: coder)
       }
       // This function will be useful when the didLoad call back arrives
       func populateWithContent(nativeAd: LevelPlayNativeAd) {
           // Assigning views contents to the nativeAdView
           if let iconImage = nativeAd.icon?.image {
               nativeAdView.adAppIcon?.image = iconImage
           } else {
               nativeAdView.adAppIcon?.removeFromSuperview()
           }
           nativeAdView.adTitleView?.text = nativeAd.title
           nativeAdView.adAdvertiserView?.text = nativeAd.advertiser
           nativeAdView.adBodyView?.text = nativeAd.body
           nativeAdView.adCallToActionView?.setTitle(nativeAd.callToAction, for: .normal)
           nativeAdView.adCallToActionView?.isUserInteractionEnabled = false
           // call function to register native ad
           nativeAdView.registerNativeAdViews(nativeAd)
       }
   }
   ```

### MediaView##mediaview

MediaView는 메인 미디어 요소 표시하기 위한 지정된 컨테이너입니다. 컨테이너에 고정 크기 제약을 사용하는 것이 좋습니다.

### 광고 투명도 향상##enhancing-ad-transparency

**개인정보 아이콘** - 이 요소는 설계 과정에서 네이티브 광고의 왼쪽 하단 모서리에 포함되어야 합니다.

**광고 표시** – 사용자가 광고임을 이해하려면 네이티브 광고를 ‘광고’로 표시해야 합니다. 직접 표시를 추가하면 됩니다.

## 4단계. 네이티브 광고 표시##step-4.-show-the-native-ad

컨테이너 뷰를 생성하고 코드의 레퍼런스 바인드. 이 뷰는 네이티브 광고 뷰의 부모 뷰가 됩니다.

```objective-c
@properties (weak, nonatomic) IBOutlet UIView *nativeAdContainer;
```

```objective-c
@IBOutlet 약점 var nativeAdContainer: UIView!
```

**didLoad** 콜백이 도착하면\*\* 광고 콘텐츠로 뷰를 채우고 컨테이너 뷰의 하위 뷰로 할당합니다.

```objective-c
-(void)didLoad:(LevelPlayNativeAd *)nativeAd
    withAdInfo:(ISAdInfo *)adInfo{
        // Populate view
        [_nativeAdView populateWithContent:nativeAd];
    
        // Nest the native ad view in the container view
        [_nativeAdContainer addSubview:_nativeAdView];
    
        // Set the constraints between the container and native ad view
        _nativeAdView.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [_nativeAdView.topAnchor constraintEqualToAnchor:_nativeAdContainer.topAnchor],
            [_nativeAdView.leadingAnchor constraintEqualToAnchor:_nativeAdContainer.leadingAnchor],
            [_nativeAdView.trailingAnchor constraintEqualToAnchor:_nativeAdContainer.trailingAnchor],
            [_nativeAdView.bottomAnchor constraintEqualToAnchor:_nativeAdContainer.bottomAnchor]
        ]];
}
```

```objective-c
func didLoad(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {
        // Populate view
        nativeAdView.populateWithContent(nativeAd: nativeAd)
        
        // Nest the native ad view in the container view
        nativeAdContainer.addSubview(nativeAdView)
        
        // Set the constraints between the container and native ad view
        nativeAdView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            nativeAdView.topAnchor.constraint(equalTo: nativeAdContainer.topAnchor),
            nativeAdView.leadingAnchor.constraint(equalTo: nativeAdContainer.leadingAnchor),
            nativeAdView.trailingAnchor.constraint(equalTo: nativeAdContainer.trailingAnchor),
            nativeAdView.bottomAnchor.constraint(equalTo: nativeAdContainer.bottomAnchor)
        ])
    }
```

4단계를 성공적으로 완료하면 사용자 네이티브 광고가 표시됩니다. 1단계를 다시 따라 새로운 LevelPlayNativeAd 오브젝트 NativeAdView를 요청합니다.

## 5단계 네이티브 광고 제거##step-5.-destroy-the-native-ad

네이티브 광고를 삭제하려면 호출 **destroyAd를 호출하고** 컨테이너 뷰에서 제거합니다.

```objective-c
[_nativeAd destroyAd];
[_nativeAdView removeFromSuperview];
```

```objective-c
nativeAd.destroy()
nativeAdView.removeFromSuperview()
```

> **Note:**
>
> 삭제된 네이티브 광고는 더 이상 로드할 수 없습니다. 다시 제공하려면 다시 시작해야 합니다.
