# iOS 向けネイティブ広告インテグレーション

> ネイティブ広告オブジェクトの作成とロード、デリゲートの実装、ビューの設計、広告コンテンツのバインディングによって、ネイティブ広告を統合します。

ネイティブ広告は、アプリケーション内の他のコンテンツに溶け込むようにカスタマイズできる広告の形式です。これにより、広告がよりオーガニックに表示され、ユーザー エクスペリエンスとリテンションの向上につながります。

## 前提条件##prerequisites

LevelPlay SDK 8.4.0 以降がアプリケーションに正しく統合されていることを確認します。インテグレーションの概要は[こちら](/grow/levelplay/sdk/ios/sdk-integration.md)です。

## ネイティブ広告の統合##integrate-native-ads

ネイティブ広告を統合するには、次の 5 つのステップに従う必要があります。 

1. ネイティブ広告オブジェクトの作成とロード
2. デリゲートの実装
3. ビューの設計とバインド
4. ネイティブ広告の表示
5. ネイティブ広告の破棄

**ステップ 1.ネイティブ広告オブジェクト**の作成とロード

1. LevelPlayNativeAdBuilder クラスを使用してネイティブの広告オブジェクトを作成します。このクラスでは、オブジェクトのカスタム設定が可能です。ネイティブ広告のロードメカニズムを 1 か所で管理するために、別のクラスを作成することをお勧めします。

   ```objective-c
   LevelPlayNativeAd *levelPlayNativeAd = [[[[LevelPlayNativeAdBuilder new] 
   withViewController:self] 
   withPlacementName:YOUR_配置_NAME] // 配置に置き換えるか、空にしておきます
   withDelegate:self]	// We implement the delegate in step 2
   .build;
   ```

   ```objective-c
   let levelPlayNativeAd:LevelPlayNativeAd = LevelPlayNativeAdBuilder()
               .withViewController(self)
               .withPlacementName(YOUR_配置_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
   @プロパティ（非アトミック、強） LevelPlayNativeAd *nativeAd;
   @プロパティ （非アトミック、強力） 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** を実装します。LevelPlay SDK は、ネイティブ広告アクティビティを通知するためにいくつかのコールバックを起動します。SDK は、以下のすべてのイベントをリスナーに通知します。

```objective-c
// LevelPlayNativeAdDelegate
/**
 ネイティブ広告が正常にロードされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */
-(void)didLoad:(LevelPlayNativeAd *)nativeAd
    withAdInfo:(ISAdInfo *)adInfo{}
/**
 ネイティブが広告のロードを試行したが失敗した後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param error エラーの理由
 */
-(void)didFailToLoad:(LevelPlayNativeAd *)nativeAd
           withError:(NSError *)error;{}
/**
 ネイティブアドインプレッションが記録された後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */
-(void)didRecordImpression:(LevelPlayNativeAd *)nativeAd
                withAdInfo:(ISAdInfo *)adInfo{}
/**
 ネイティブ広告がクリックされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */
-(void)didClick:(LevelPlayNativeAd *)nativeAd
     withAdInfo:(ISAdInfo *)adInfo;{}
```

```objective-c
// LevelPlayNativeAdDelegate
/**
 ネイティブ広告が正常にロードされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */ 
func didLoad(_ nativeAd:LevelPlayNativeAd、adInfo あり：ISAdInfo) {}
/**
 ネイティブが広告のロードを試行したが失敗した後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param error エラーの理由
 */    
func didFail(_ nativeAd:LevelPlayNativeAd、withError エラー:Error) {}
 
/**
 ネイティブアドインプレッションが記録された後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */   
func didRecordImpression(_ nativeAd:LevelPlayNativeAd、adInfo あり：ISAdInfo) {}
   
/**
 ネイティブ広告がクリックされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */ 
func didClick(_ nativeAd:LevelPlayNativeAd、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
   @プロパティ（非アトミック、高強度） ISNativeAdView *nativeAdView;
   - (void)populateWithContent:(nonnull LevelPlayNativeAd *)nativeAd;
   @end
   @implementation NativeAdView
   - (instancetype)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
   import UIKit
   import IronSource
   class NativeAdView:UIView {
       private var nativeAdView:ISNativeAdView!
       
       override init(frame: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?(コーダー: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

**プライバシーアイコン** - この要素は、設計プロセス中にネイティブ広告の左下隅に組み込む必要があります。

**広告表示** – これが広告であることをユーザーに理解してもらうために、ネイティブ広告を「Ad」としてマークする必要があります。これは独自の指示を追加することで実現できます。

## ステップ 4. ネイティブ広告の表示##step-4.-show-the-native-ad

コンテナビューを作成し、コード内のリファレンスにバインドします。このビューはネイティブ広告ビューの親ビューになります。

```objective-c
@プロパティ （weak、nonatomic） IBOutlet UIView *nativeAdContainer;
```

```objective-c
@IBOutlet weak 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、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:**
>
> 破棄されたネイティブ広告はロードできません。再度配信したい場合は、再度開始する必要があります。
