FC2ブログ

記事一覧

nendでバナー広告を表示する方法 -iOS編- | Xamarin.Forms


今回はXamarin.iOSの開発環境でnendのSDKを使用してバナー広告を表示する方法についてご紹介いたします。
nendは日本でのスマホ専用広告配信ができるパートナー様ですが、広告を表示する為のSDKがXamarinの正式対応をしておらず、NendAd.frameworkフォルダのバインド方法やObjectiveSharpieの使用方法など最初はわからず大変苦労しましたが、手順が判明した結果簡単に実装ができることが分かりました。
尚、Xamarin.Androidでの実装方法は前回の記事「nendでバナー広告を表示する方法 -Android編-」をご参考ください。


ExplorerDx
xamarin_nend_ios_01.png
ContactFriends
xamarin_nend_ios_02.png



前提条件
・Windows10 Pro 64Bit
・Visual Studio 2015 Community Update3
・Xamarin 4.3.0.795 (NuGet Xamarin.Forms 2.3.4.247)
・macOS Sierra 10.12.4 / Xcode8.3.1 / Xamarin.iOS 10.6.0.10



1.nendの登録

以下のサイトで登録できます。
https://www.nend.net/
全て日本語なので登録しやすいですね。

xamarin_nend_03.png


(1)広告枠の管理からAndroidアプリを登録します。

(2)アプリが登録できたらアプリに広告枠を追加します。
タイプ:バナー
広告枠名:任意
広告枠の形式:インライン フッター
広告枠のサイズ:320×50

尚、広告枠は作成毎に審査があります。
2営業日程待たなくてはいけません。

(3)SDKをダウンロードします。
https://www.nend.net/m/sdk

(4)NendSDK_iOS-3.3.3.zipファイルを解凍すると
内部にNendAd.frameworkというフォルダが取得できます。

(5)NendAdファイルをリネームして拡張子「a」を付けます。
リネーム後:「NendAd.a
※ファイルの場所は以下に保存されています。
\NendSDK_iOS-3.3.3\Nend\NendAd\NendAd.embeddedframework\NendAd.framework\NendAd



2.SDKの組み込み方法

(1)Visual Studioでバインドライブラリプロジェクトを作成します。
frameworkフォルダやaファイルなどのXcodeで作成されたファイルはバインドライブラリのプロジェクトを使用すると簡単にObjective-CからC#に変換できます。
 xamarin_nend_ios_03.png


(2)ソリューションエクスプローラを開き、バインドライブラリ内のトップディレクトリにリネームしたaファイル「NendAd.a」ファイルをドラッグ&ドロップします。


(3)ビルドアクションを 「ObjcBindingNativeLibrary」に変更します。

xamarin_nend_ios_04.png 


(4)Objective Sharpieを使用して以下の変換定義ファイルを作成します。
ApiDefinitions.cs
StructsAndEnums.cs


ダウンロードしたSDKのframeworkフォルダをMac上にコピーし、ターミナルからsharpie bind コマンドで frameworkフォルダ内のHeaderファイル群を読み込みます。
※作成する方法は以前の記事「Objective Sharpieの使用方法」をご参考ください。
 

(5)変換定義ファイルをバインドライブラリプロジェクトのトップディレクトリに配置します。

xamarin_nend_ios_05.png


(6)変換定義ファイルのビルドアクションを変更します。
ApiDefinitions.cs       : ObjcBindingApiDefinition
StructsAndEnums.cs : ObjcBindingCoreSource


(7)変換定義ファイルを修正します。
Objective Sharpieで作成された定義ファイルが正確でないため、修正します。
基本的には以下のように変更していきます。

ApiDefinitions.cs
・interface は public interface に変更
・string は NSString に変更
・***Delegate @***Delegate という引数名称を ***Delegate @p1 というカンジで名称変更
・[Verify]は全てコメントアウト
・[Static]も全てコメントアウト

StructsAndEnums.cs
・nint は long に変更
・enum は public enum に変更


(8)修正後のファイル

ApiDefinitions.cs
using System;
using CoreGraphics;
using Foundation;
using Nend.iOS;
using ObjCRuntime;
using UIKit;
namespace Nend.iOS
{
    // @protocol NADFullBoardViewDelegate <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADFullBoardViewDelegate
    {
        // @optional -(void)NADFullBoardDidClickAd:(NADFullBoard *)ad;
        [Export ("NADFullBoardDidClickAd:")]
        void NADFullBoardDidClickAd (NADFullBoard ad);
    }

    // @protocol NADFullBoardView <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADFullBoardView

    {
        [Wrap ("WeakDelegate")] //ishikawa  //, Abstract]
        NADFullBoardViewDelegate Delegate { get; set; }

        // @required @property (nonatomic, weak) id<NADFullBoardViewDelegate> delegate;
        [Abstract]
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        //// @required -(void)enableCloseButtonWithClickHandler:(dispatch_block_t)handler;
        //[Abstract]
        //[Export ("enableCloseButtonWithClickHandler:")]
        //void EnableCloseButtonWithClickHandler (dispatch_block_t handler);
    }

    // @protocol NADFullBoardDelegate <NADFullBoardViewDelegate>
    [Protocol, Model]
    [BaseType(typeof(NSObject))]
    public interface NADFullBoardDelegate : NADFullBoardViewDelegate
    {
        // @optional -(void)NADFullBoardDidShowAd:(NADFullBoard *)ad;
        [Export ("NADFullBoardDidShowAd:")]
        void NADFullBoardDidShowAd (NADFullBoard ad);

        // @optional -(void)NADFullBoardDidDismissAd:(NADFullBoard *)ad;
        [Export ("NADFullBoardDidDismissAd:")]
        void NADFullBoardDidDismissAd (NADFullBoard ad);
    }

    // @interface NADFullBoard : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADFullBoard
    {
        [Wrap ("WeakDelegate")]
        NADFullBoardDelegate Delegate { get; set; }

        // @property (nonatomic, weak) id<NADFullBoardDelegate> delegate;
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        // -(void)showFromViewController:(UIViewController *)viewController;
        [Export ("showFromViewController:")]
        void ShowFromViewController (UIViewController viewController);

        // -(UIViewController<NADFullBoardView> *)fullBoardAdViewController;
        [Export ("fullBoardAdViewController")]
        //[Verify (MethodToProperty)]
        NADFullBoardView FullBoardAdViewController { get; }

        // -(void)showInViewController:(UIViewController *)viewController layoutType:(NADFullBoardLayoutType)type __attribute__((deprecated("This method has been replaced by showFromViewController:")));
        [Export ("showInViewController:layoutType:")]
        void ShowInViewController (UIViewController viewController, NADFullBoardLayoutType type);

        // -(UIViewController<NADFullBoardView> *)fullScreenAdViewControllerWithType:(NADFullBoardLayoutType)type __attribute__((deprecated("This method has been replaced by fullBoardAdViewController")));
        [Export ("fullScreenAdViewControllerWithType:")]
        NADFullBoardView FullScreenAdViewControllerWithType (NADFullBoardLayoutType type);
    }

    // typedef void (^NADFullBoardLoaderCompletionHandler)(NADFullBoard *, NADFullBoardLoaderError);
    public delegate void NADFullBoardLoaderCompletionHandler (NADFullBoard arg0, NADFullBoardLoaderError arg1);

    // @interface NADFullBoardLoader : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADFullBoardLoader
    {
        // -(instancetype)initWithSpotId:(NSString *)spotId apiKey:(NSString *)apiKey;
        [Export ("initWithSpotId:apiKey:")]
        IntPtr Constructor (NSString spotId, NSString apiKey);

        // -(void)loadAdWithCompletionHandler:(NADFullBoardLoaderCompletionHandler)handler;
        [Export ("loadAdWithCompletionHandler:")]
        void LoadAdWithCompletionHandler (NADFullBoardLoaderCompletionHandler handler);
    }

    // @protocol NADInterstitialDelegate <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADInterstitialDelegate
    {
        // @optional -(void)didFinishLoadInterstitialAdWithStatus:(NADInterstitialStatusCode)status;
        [Export ("didFinishLoadInterstitialAdWithStatus:")]
        void DidFinishLoadInterstitialAdWithStatus (NADInterstitialStatusCode status);

        // @optional -(void)didFinishLoadInterstitialAdWithStatus:(NADInterstitialStatusCode)status spotId:(NSString *)spotId;
        [Export ("didFinishLoadInterstitialAdWithStatus:spotId:")]
        void DidFinishLoadInterstitialAdWithStatus (NADInterstitialStatusCode status, NSString spotId);

        // @optional -(void)didClickWithType:(NADInterstitialClickType)type;
        [Export ("didClickWithType:")]
        void DidClickWithType (NADInterstitialClickType type);

        // @optional -(void)didClickWithType:(NADInterstitialClickType)type spotId:(NSString *)spotId;
        [Export ("didClickWithType:spotId:")]
        void DidClickWithType (NADInterstitialClickType type, NSString spotId);
    }

    // @interface NADInterstitial : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADInterstitial
    {
        [Wrap ("WeakDelegate")]
        NADInterstitialDelegate Delegate { get; set; }

        // @property (readwrite, nonatomic, weak) id<NADInterstitialDelegate> delegate;
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        // @property (nonatomic) BOOL isOutputLog;
        [Export ("isOutputLog")]
        bool IsOutputLog { get; set; }

        // @property (nonatomic) BOOL enableAutoReload;
        [Export ("enableAutoReload")]
        bool EnableAutoReload { get; set; }

        // @property (nonatomic) NSArray * supportedOrientations __attribute__((deprecated("Not used.")));
        [Export ("supportedOrientations", ArgumentSemantic.Assign)]
        //[Verify (StronglyTypedNSArray)]
        NSObject[] SupportedOrientations { get; set; }

        // +(instancetype)sharedInstance;
        //[Static]
        [Export ("sharedInstance")]
        NADInterstitial SharedInstance ();

        // -(void)loadAdWithApiKey:(NSString *)apiKey spotId:(NSString *)spotId;
        [Export ("loadAdWithApiKey:spotId:")]
        void LoadAdWithApiKey (NSString apiKey, NSString spotId);

        // -(NADInterstitialShowResult)showAd __attribute__((deprecated("This method has been replaced by showAdFromViewController:")));
        [Export ("showAd")]
        //[Verify (MethodToProperty)]
        NADInterstitialShowResult ShowAd { get; }

        // -(NADInterstitialShowResult)showAdWithSpotId:(NSString *)spotId __attribute__((deprecated("This method has been replaced by showAdFromViewController:spotId:")));
        [Export ("showAdWithSpotId:")]
        NADInterstitialShowResult ShowAdWithSpotId (NSString spotId);

        // -(NADInterstitialShowResult)showAdFromViewController:(UIViewController *)viewController;
        [Export ("showAdFromViewController:")]
        NADInterstitialShowResult ShowAdFromViewController (UIViewController viewController);

        // -(NADInterstitialShowResult)showAdFromViewController:(UIViewController *)viewController spotId:(NSString *)spotId;
        [Export ("showAdFromViewController:spotId:")]
        NADInterstitialShowResult ShowAdFromViewController (UIViewController viewController, NSString spotId);

        // -(BOOL)dismissAd;
        [Export ("dismissAd")]
        //[Verify (MethodToProperty)]
        bool DismissAd { get; }
    }

    // @interface NADNativeImageView : UIImageView
    [BaseType (typeof(UIImageView))]
    public interface NADNativeImageView
    {
    }

    // @interface NADNativeLabel : UILabel
    [BaseType (typeof(UILabel))]
    public interface NADNativeLabel
    {
    }

    // @protocol NADNativeViewRendering <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADNativeViewRendering
    {
        // @required -(UILabel *)prTextLabel;
        [Abstract]
        [Export ("prTextLabel")]
        //[Verify (MethodToProperty)]
        UILabel PrTextLabel { get; }

        // @optional -(UIImageView *)adImageView;
        [Export ("adImageView")]
        //[Verify (MethodToProperty)]
        UIImageView AdImageView { get; }

        // @optional -(UIImageView *)nadLogoImageView;
        [Export ("nadLogoImageView")]
        //[Verify (MethodToProperty)]
        UIImageView NadLogoImageView { get; }

        // @optional -(UILabel *)shortTextLabel;
        [Export ("shortTextLabel")]
        //[Verify (MethodToProperty)]
        UILabel ShortTextLabel { get; }

        // @optional -(UILabel *)longTextLabel;
        [Export ("longTextLabel")]
        //[Verify (MethodToProperty)]
        UILabel LongTextLabel { get; }

        // @optional -(UILabel *)promotionUrlLabel;
        [Export ("promotionUrlLabel")]
        //[Verify (MethodToProperty)]
        UILabel PromotionUrlLabel { get; }

        // @optional -(UILabel *)promotionNameLabel;
        [Export ("promotionNameLabel")]
        //[Verify (MethodToProperty)]
        UILabel PromotionNameLabel { get; }

        // @optional -(UILabel *)actionButtonTextLabel;
        [Export ("actionButtonTextLabel")]
        //[Verify (MethodToProperty)]
        UILabel ActionButtonTextLabel { get; }
    }

    // typedef void (^NADNativeImageCompletionBlock)(UIImage *);
    public delegate void NADNativeImageCompletionBlock (UIImage arg0);

    // @protocol NADNativeDelegate <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADNativeDelegate
    {
        // @optional -(void)nadNativeDidClickAd:(NADNative *)ad;
        [Export ("nadNativeDidClickAd:")]
        void NadNativeDidClickAd (NADNative ad);

        // @optional -(void)nadNativeDidDisplayAd:(NADNative *)ad success:(BOOL)success __attribute__((deprecated("")));
        [Export ("nadNativeDidDisplayAd:success:")]
        void NadNativeDidDisplayAd (NADNative ad, bool success);
    }

    // @interface NADNative : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADNative
    {
        // @property (readonly, copy, nonatomic) NSString * shortText;
        [Export ("shortText")]
        NSString ShortText { get; }

        // @property (readonly, copy, nonatomic) NSString * longText;
        [Export ("longText")]
        NSString LongText { get; }

        // @property (readonly, copy, nonatomic) NSString * promotionUrl;
        [Export ("promotionUrl")]
        NSString PromotionUrl { get; }

        // @property (readonly, copy, nonatomic) NSString * promotionName;
        [Export ("promotionName")]
        NSString PromotionName { get; }

        // @property (readonly, copy, nonatomic) NSString * actionButtonText;
        [Export ("actionButtonText")]
        NSString ActionButtonText { get; }

        // @property (readonly, copy, nonatomic) NSString * imageUrl;
        [Export ("imageUrl")]
        NSString ImageUrl { get; }

        // @property (readonly, copy, nonatomic) NSString * logoUrl;
        [Export ("logoUrl")]
        NSString LogoUrl { get; }

        [Wrap ("WeakDelegate")]
        NADNativeDelegate Delegate { get; set; }

        // @property (nonatomic, weak) id<NADNativeDelegate> delegate;
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        // -(void)intoView:(UIView<NADNativeViewRendering> *)view advertisingExplicitly:(NADNativeAdvertisingExplicitly)advertisingExplicitly;
        [Export ("intoView:advertisingExplicitly:")]
        void IntoView (NADNativeViewRendering view, NADNativeAdvertisingExplicitly advertisingExplicitly);

        // -(NSString *)prTextForAdvertisingExplicitly:(NADNativeAdvertisingExplicitly)advertisingExplicitly;
        [Export ("prTextForAdvertisingExplicitly:")]
        NSString PrTextForAdvertisingExplicitly (NADNativeAdvertisingExplicitly advertisingExplicitly);

        // -(void)activateAdView:(UIView *)view withPrLabel:(UILabel *)prLabel;
        [Export ("activateAdView:withPrLabel:")]
        void ActivateAdView (UIView view, UILabel prLabel);

        // -(void)loadAdImageWithCompletionBlock:(NADNativeImageCompletionBlock)block;
        [Export ("loadAdImageWithCompletionBlock:")]
        void LoadAdImageWithCompletionBlock (NADNativeImageCompletionBlock block);

        // -(void)loadLogoImageWithCompletionBlock:(NADNativeImageCompletionBlock)block;
        [Export ("loadLogoImageWithCompletionBlock:")]
        void LoadLogoImageWithCompletionBlock (NADNativeImageCompletionBlock block);
    }

    //[Static]
    //[Verify (ConstantsInterfaceAssociation)]
    partial interface Constants
    {
        // extern NSString *const kNADNativeErrorDomain;
        [Field ("kNADNativeErrorDomain", "__Internal")]
        NSString kNADNativeErrorDomain { get; }

        // extern const NSInteger kNADNativeErrorCodeExcessiveAdCalls;
        [Field ("kNADNativeErrorCodeExcessiveAdCalls", "__Internal")]
        nint kNADNativeErrorCodeExcessiveAdCalls { get; }

        // extern const NSInteger kNADNativeErrorCodeFailedToRequest;
        [Field ("kNADNativeErrorCodeFailedToRequest", "__Internal")]
        nint kNADNativeErrorCodeFailedToRequest { get; }

        // extern const NSInteger kNADNativeErrorCodeInvalidResponseType;
        [Field ("kNADNativeErrorCodeInvalidResponseType", "__Internal")]
        nint kNADNativeErrorCodeInvalidResponseType { get; }
    }

    // @interface NADNativeError : NSError
    [BaseType (typeof(NSError))]
    public interface NADNativeError
    {
    }

    // @interface NADNativeLogger : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADNativeLogger
    {
        // +(void)setLogLevel:(NADNativeLogLevel)level;
        //[Static]
        [Export ("setLogLevel:")]
        void SetLogLevel (NADNativeLogLevel level);
    }

    // typedef void (^NADNativeCompletionBlock)(NADNative *, NSError *);
    public delegate void NADNativeCompletionBlock (NADNative arg0, NSError arg1);

    // @interface NADNativeClient : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADNativeClient
    {
        [Wrap ("WeakDelegate")]
        NADNativeDelegate Delegate { get; set; }

        // @property (nonatomic, weak) id<NADNativeDelegate> delegate __attribute__((deprecated("Please use the delegate of NADNative class instead.")));
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        // -(instancetype)initWithSpotId:(NSString *)spotId apiKey:(NSString *)apiKey;
        [Export ("initWithSpotId:apiKey:")]
        IntPtr Constructor (NSString spotId, NSString apiKey);

        // -(void)loadWithCompletionBlock:(NADNativeCompletionBlock)completionBlock;
        [Export ("loadWithCompletionBlock:")]
        void LoadWithCompletionBlock (NADNativeCompletionBlock completionBlock);

        // -(void)enableAutoReloadWithInterval:(NSTimeInterval)interval completionBlock:(NADNativeCompletionBlock)completionBlock;
        [Export ("enableAutoReloadWithInterval:completionBlock:")]
        void EnableAutoReloadWithInterval (double interval, NADNativeCompletionBlock completionBlock);

        // -(void)disableAutoReload;
        [Export ("disableAutoReload")]
        void DisableAutoReload ();
    }

    // @interface NADNativeTableViewPlacement : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADNativeTableViewPlacement
    {
        // -(void)addFixedIndexPath:(NSIndexPath *)indexPath;
        [Export ("addFixedIndexPath:")]
        void AddFixedIndexPath (NSIndexPath indexPath);

        // -(void)addFixedIndexPath:(NSIndexPath *)indexPath fillRow:(BOOL)fillRow;
        [Export ("addFixedIndexPath:fillRow:")]
        void AddFixedIndexPath (NSIndexPath indexPath, bool fillRow);

        // -(void)addFixedIndexPath:(NSIndexPath *)indexPath adCount:(NSUInteger)adCount;
        [Export ("addFixedIndexPath:adCount:")]
        void AddFixedIndexPath (NSIndexPath indexPath, nuint adCount);

        // -(void)addFixedIndexPath:(NSIndexPath *)indexPath fillRow:(BOOL)fillRow adCount:(NSUInteger)adCount;
        [Export ("addFixedIndexPath:fillRow:adCount:")]
        void AddFixedIndexPath (NSIndexPath indexPath, bool fillRow, nuint adCount);

        // -(void)addRepeatInterval:(NSUInteger)interval inSection:(NSUInteger)section;
        [Export ("addRepeatInterval:inSection:")]
        void AddRepeatInterval (nuint interval, nuint section);

        // -(void)addRepeatInterval:(NSUInteger)interval inSection:(NSUInteger)section fillRow:(BOOL)fillRow;
        [Export ("addRepeatInterval:inSection:fillRow:")]
        void AddRepeatInterval (nuint interval, nuint section, bool fillRow);

        // -(void)addRepeatInterval:(NSUInteger)interval inSection:(NSUInteger)section adCount:(NSUInteger)adCount;
        [Export ("addRepeatInterval:inSection:adCount:")]
        void AddRepeatInterval (nuint interval, nuint section, nuint adCount);

        // -(void)addRepeatInterval:(NSUInteger)interval inSection:(NSUInteger)section fillRow:(BOOL)fillRow adCount:(NSUInteger)adCount;
        [Export ("addRepeatInterval:inSection:fillRow:adCount:")]
        void AddRepeatInterval (nuint interval, nuint section, bool fillRow, nuint adCount);
    }

    // @protocol NADNativeTableViewHelperDelegate <NADNativeDelegate>
    [Protocol, Model]
    [BaseType(typeof(NSObject))]
    public interface NADNativeTableViewHelperDelegate : NADNativeDelegate
    {
        // @required -(UITableViewCell *)tableView:(UITableView *)tableView adCellForRowAtIndexPath:(NSIndexPath *)indexPath;
        [Abstract]
        [Export("tableView:adCellForRowAtIndexPath:")]
        UITableViewCell TableView(UITableView tableView, NSIndexPath indexPath);

        //// @required -(CGFloat)tableView:(UITableView *)tableView heightForAdRowAtIndexPath:(NSIndexPath *)indexPath;
        //[Abstract]
        //[Export("tableView:heightForAdRowAtIndexPath:")]
        //nfloat TableView(UITableView tableView, NSIndexPath indexPath);

        //// @optional -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForAdRowAtIndexPath:(NSIndexPath *)indexPath;
        //[Export("tableView:estimatedHeightForAdRowAtIndexPath:")]
        //nfloat TableView(UITableView tableView, NSIndexPath indexPath);
    }

    // @interface NADNativeTableViewHelper : NSObject
    [BaseType (typeof(NSObject))]
    public interface NADNativeTableViewHelper
    {
        // +(instancetype)helperWithTableView:(UITableView *)tableView spotId:(NSString *)spotId apiKey:(NSString *)apiKey advertisingExplicitly:(NADNativeAdvertisingExplicitly)advertisingExplicitly adPlacement:(NADNativeTableViewPlacement *)adPlacement delegate:(id<NADNativeTableViewHelperDelegate>)delegate;
        //[Static]
        [Export ("helperWithTableView:spotId:apiKey:advertisingExplicitly:adPlacement:delegate:")]
        NADNativeTableViewHelper HelperWithTableView (UITableView tableView, NSString spotId, NSString apiKey, NADNativeAdvertisingExplicitly advertisingExplicitly, NADNativeTableViewPlacement adPlacement, NADNativeTableViewHelperDelegate @tvhd1);

        // +(instancetype)helperWithTableView:(UITableView *)tableView spotId:(NSString *)spotId apiKey:(NSString *)apiKey advertisingExplicitly:(NADNativeAdvertisingExplicitly)advertisingExplicitly adPlacement:(NADNativeTableViewPlacement *)adPlacement delegate:(id<NADNativeTableViewHelperDelegate>)delegate placeholderCellClass:(Class)placeholderCellClass;
        //[Static]
        [Export ("helperWithTableView:spotId:apiKey:advertisingExplicitly:adPlacement:delegate:placeholderCellClass:")]
        NADNativeTableViewHelper HelperWithTableView (UITableView tableView, NSString spotId, NSString apiKey, NADNativeAdvertisingExplicitly advertisingExplicitly, NADNativeTableViewPlacement adPlacement, NADNativeTableViewHelperDelegate @tvhd2, Class placeholderCellClass);

        // +(instancetype)helperWithTableView:(UITableView *)tableView spotId:(NSString *)spotId apiKey:(NSString *)apiKey advertisingExplicitly:(NADNativeAdvertisingExplicitly)advertisingExplicitly adPlacement:(NADNativeTableViewPlacement *)adPlacement delegate:(id<NADNativeTableViewHelperDelegate>)delegate placeholderCellNibName:(NSString *)placeholderCellNibName;
        //[Static]
        [Export ("helperWithTableView:spotId:apiKey:advertisingExplicitly:adPlacement:delegate:placeholderCellNibName:")]
        NADNativeTableViewHelper HelperWithTableView (UITableView tableView, NSString spotId, NSString apiKey, NADNativeAdvertisingExplicitly advertisingExplicitly, NADNativeTableViewPlacement adPlacement, NADNativeTableViewHelperDelegate @tvhd3, NSString placeholderCellNibName);
    }

    // @interface IndexPathManipulations (NADNativeTableViewHelper)
    [Category]
    [BaseType (typeof(NADNativeTableViewHelper))]
    public interface NADNativeTableViewHelper_IndexPathManipulations
    {
        // -(NSIndexPath *)originalIndexPathForActualIndexPath:(NSIndexPath *)indexPath;
        [Export ("originalIndexPathForActualIndexPath:")]
        NSIndexPath OriginalIndexPathForActualIndexPath (NSIndexPath indexPath);

        // -(NSIndexPath *)actualIndexPathForOriginalIndexPath:(NSIndexPath *)indexPath;
        [Export ("actualIndexPathForOriginalIndexPath:")]
        NSIndexPath ActualIndexPathForOriginalIndexPath (NSIndexPath indexPath);
    }

    // @protocol NADViewDelegate <NSObject>
    [Protocol, Model]
    [BaseType (typeof(NSObject))]
    public interface NADViewDelegate
    {
        // @optional -(void)nadViewDidFinishLoad:(NADView *)adView;
        [Export ("nadViewDidFinishLoad:")]
        void NadViewDidFinishLoad (NADView adView);

        // @optional -(void)nadViewDidReceiveAd:(NADView *)adView;
        [Export ("nadViewDidReceiveAd:")]
        void NadViewDidReceiveAd (NADView adView);

        // @optional -(void)nadViewDidFailToReceiveAd:(NADView *)adView;
        [Export ("nadViewDidFailToReceiveAd:")]
        void NadViewDidFailToReceiveAd (NADView adView);

        // @optional -(void)nadViewDidClickAd:(NADView *)adView;
        [Export ("nadViewDidClickAd:")]
        void NadViewDidClickAd (NADView adView);

        // @optional -(void)nadViewDidClickInformation:(NADView *)adView;
        [Export ("nadViewDidClickInformation:")]
        void NadViewDidClickInformation (NADView adView);
    }

    // @interface NADView : UIView
    [BaseType (typeof(UIView))]
    public interface NADView
    {
        [Wrap ("WeakDelegate")]
        NADViewDelegate Delegate { get; set; }

        // @property (nonatomic, weak) id<NADViewDelegate> delegate;
        [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
        NSObject WeakDelegate { get; set; }

        // @property (nonatomic) BOOL isOutputLog;
        [Export ("isOutputLog")]
        bool IsOutputLog { get; set; }

        // @property (nonatomic) NSError * error;
        [Export ("error", ArgumentSemantic.Assign)]
        NSError Error { get; set; }

        // @property (copy, nonatomic) NSString * nendApiKey;
        [Export ("nendApiKey")]
        NSString NendApiKey { get; set; }

        // @property (copy, nonatomic) NSString * nendSpotID;
        [Export ("nendSpotID")]
        NSString NendSpotID { get; set; }

        // -(instancetype)initWithIsAdjustAdSize:(BOOL)isAdjust;
        [Export ("initWithIsAdjustAdSize:")]
        IntPtr Constructor (bool isAdjust);

        // -(instancetype)initWithFrame:(CGRect)frame isAdjustAdSize:(BOOL)isAdjust;
        [Export ("initWithFrame:isAdjustAdSize:")]
        IntPtr Constructor (CGRect frame, bool isAdjust);

        // -(void)setNendID:(NSString *)apiKey spotID:(NSString *)spotID;
        [Export ("setNendID:spotID:")]
        void SetNendID (NSString apiKey, NSString spotID);

        // -(void)load;
        [Export ("load")]
        void Load ();

        // -(void)load:(NSDictionary *)parameter;
        [Export ("load:")]
        void Load (NSDictionary parameter);

        // -(void)pause;
        [Export ("pause")]
        void Pause ();

        // -(void)resume;
        [Export ("resume")]
        void Resume ();
    }

    //[Static]
    //[Verify (ConstantsInterfaceAssociation)]
    partial interface Constants
    {
        // extern double NendAdVersionNumber;
        [Field ("NendAdVersionNumber", "__Internal")]
        double NendAdVersionNumber { get; }

        // extern const unsigned char [] NendAdVersionString;
        [Field ("NendAdVersionString", "__Internal")]
        byte[] NendAdVersionString { get; }
    }
}


StructsAndEnums.cs
using System;
using ObjCRuntime;
namespace Nend.iOS
{
    [Native]
    public enum NADFullBoardLayoutType : long  //nint
    {
        Top,
        Middle
    }

    [Native]
    public enum NADFullBoardLoaderError : long  //nint
    {
        None,
        FailedAdRequest,
        InvalidAdSpaces,
        FailedDownloadImage
    }

    [Native]
    public enum NADInterstitialClickType : long  //nint
    {
        Download,
        Close,
        Information
    }

    [Native]
    public enum NADInterstitialStatusCode : long  //nint
    {
        Success,
        InvalidResponseType,
        FailedAdRequest,
        FailedAdDownload
    }

    [Native]
    public enum NADInterstitialShowResult : long  //nint
    {
        ShowSuccess,
        LoadIncomplete,
        RequestIncomplete,
        DownloadIncomplete,
        FrequencyNotReachable,
        ShowAlready,
        CannotDisplay
    }

    [Native]
    public enum NADNativeAdvertisingExplicitly : long  //nint
    {
        Pr,
        Sponsored,
        Ad,
        Promotion
    }

    [Native]
    public enum NADNativeLogLevel : long  //nint
    {
        Debug = 1,
        Info = 2,
        Warn = 3,
        Error = 4,
        None = 2147483647
    }

    [Native]
    public enum NADViewErrorCode : long  //nint
    {
        AdSizeTooLarge,
        InvalidResponseType,
        FailedAdRequest,
        FailedAdDownload,
        AdSizeDifferences
    }
}


(9)バインドライブラリプロジェクトのプロパティを設定します。
バインドライブラリ→プロパティ→ビルド→「コードの最適化」のチェックをONにします。
この設定をしないと実行時に「Invalid IL code in Nend.iOS.NADView:.ctor (CoreGraphics.CGRect,bool): IL_002b: stloc.0」というエラーが発生します。

xamarin_nend_ios_06.png


(10)iOSアプリのプロジェクトから参照設定を行います。
参照を追加で、iOSバインドライブラリを参照に追加します。



3.広告を表示


iOSプロジェクト内にレンダラーを作成して表示します。
AdBannerクラスはXamarin.Forms.Viewを継承して作成したクラスをPCLのXAMLまたはC#などで画面に配置してください。

AdBannerRenderer.cs
using UIKit;
using CoreGraphics;
using Foundation;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(AdBanner), typeof(AdBannerRenderer))]
namespace AppName.iOS.Renderer
{
    public class AdBannerRenderer : ViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
            {               
                //nend
                this.ShowNendBanner(999999, ”9999999a99999999aa9999a999”);
            }
        }

        /// <summary>
/// nendによる広告を表示する
/// </summary>
/// <param name="spotID">spotID</param>
/// <param name="apiKey">apiKey</param>
private void ShowNendBanner(int spotID, string apiKey)
{
try
{
//nend
// 1 NendAdView をインスタンス化
Nend.iOS.NADView nendAdView =
new Nend.iOS.NADView(new CGRect(0, 0, 320, 50), true);
nendAdView.NendSpotID = new NSString(spotID.ToString());
nendAdView.NendApiKey = new NSString(apiKey);
nendAdView.IsOutputLog = true;

base.SetNativeControl(nendAdView);

// 3 広告の取得を開始
//var dict = new NSDictionary(@"3600", @"retry", null); //60分毎にリロード
//nendAdView.Load(dict);
nendAdView.Load();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + System.Environment.NewLine + ex.StackTrace);
}
}
    }
}

※spotIDとapiKeyは以下のURLから取得できます。
https://www.nend.net/m/adspot
SDKボタンから確認できます。



4.注意点

(1)nendは日本語の広告のみ対応です。
海外の広告は対応していません。
多言語化(ローカライズ)しているアプリでは、設定している言語が日本語の場合のみに表示をした方が良いでしょう。

(2)nendはスマホ専用です。
PCや他のデバイスで閲覧した場合は広告が表示されません。

(3)バインドライブラリを参照設定してもオブジェクトブラウザに名前空間以降が表示されない場合やソースコードでエラーが出る場合はDLLを直接参照設定することで改善される場合があります。




最後までお読みいただきありがとうございます。
当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
http://itblogdsi.blog.fc2.com/blog-entry-81.html


関連記事

コメント

コメントの投稿

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語・データベース】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
Oracle10g SQLServer2008R2 SQLAnywhere8/11/16
ActiveReport CrystalReport ReportNet(IBM)
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。