MAUnityAdManager.m 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067
  1. //
  2. // MAUnityAdManager.m
  3. // AppLovin MAX Unity Plugin
  4. //
  5. #import "MAUnityAdManager.h"
  6. #define KEY_WINDOW [UIApplication sharedApplication].keyWindow
  7. #define DEVICE_SPECIFIC_ADVIEW_AD_FORMAT ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) ? MAAdFormat.leader : MAAdFormat.banner
  8. #define IS_VERTICAL_BANNER_POSITION(_POS) ( [@"center_left" isEqual: adViewPosition] || [@"center_right" isEqual: adViewPosition] )
  9. #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
  10. #ifdef __cplusplus
  11. extern "C" {
  12. #endif
  13. extern bool max_unity_should_disable_all_logs(void); // Forward declaration
  14. // UnityAppController.mm
  15. UIViewController* UnityGetGLViewController(void);
  16. UIWindow* UnityGetMainWindow(void);
  17. // life cycle management
  18. int UnityIsPaused(void);
  19. void UnityPause(int pause);
  20. void max_unity_dispatch_on_main_thread(dispatch_block_t block)
  21. {
  22. if ( block )
  23. {
  24. if ( [NSThread isMainThread] )
  25. {
  26. block();
  27. }
  28. else
  29. {
  30. dispatch_async(dispatch_get_main_queue(), block);
  31. }
  32. }
  33. }
  34. #ifdef __cplusplus
  35. }
  36. #endif
  37. @interface MAUnityAdManager()<MAAdDelegate, MAAdViewAdDelegate, MARewardedAdDelegate, MAAdRevenueDelegate, MAAdReviewDelegate, MAAdExpirationDelegate>
  38. // Parent Fields
  39. @property (nonatomic, weak) ALSdk *sdk;
  40. // Fullscreen Ad Fields
  41. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAInterstitialAd *> *interstitials;
  42. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAAppOpenAd *> *appOpenAds;
  43. @property (nonatomic, strong) NSMutableDictionary<NSString *, MARewardedAd *> *rewardedAds;
  44. // AdView Fields
  45. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAAdView *> *adViews;
  46. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAAdFormat *> *adViewAdFormats;
  47. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *adViewPositions;
  48. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSValue *> *adViewOffsets;
  49. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *adViewWidths;
  50. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAAdFormat *> *verticalAdViewFormats;
  51. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSArray<NSLayoutConstraint *> *> *adViewConstraints;
  52. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSString *> *> *adViewExtraParametersToSetAfterCreate;
  53. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, id> *> *adViewLocalExtraParametersToSetAfterCreate;
  54. @property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *adViewCustomDataToSetAfterCreate;
  55. @property (nonatomic, strong) NSMutableArray<NSString *> *adUnitIdentifiersToShowAfterCreate;
  56. @property (nonatomic, strong) NSMutableSet<NSString *> *disabledAdaptiveBannerAdUnitIdentifiers;
  57. @property (nonatomic, strong) NSMutableSet<NSString *> *disabledAutoRefreshAdViewAdUnitIdentifiers;
  58. @property (nonatomic, strong) NSMutableSet<NSString *> *ignoreSafeAreaLandscapeAdUnitIdentifiers;
  59. @property (nonatomic, strong) UIView *safeAreaBackground;
  60. @property (nonatomic, strong, nullable) UIColor *publisherBannerBackgroundColor;
  61. @property (nonatomic, strong) NSMutableDictionary<NSString *, MAAd *> *adInfoDict;
  62. @property (nonatomic, strong) NSObject *adInfoDictLock;
  63. @property (nonatomic, strong) NSOperationQueue *backgroundCallbackEventsQueue;
  64. @property (nonatomic, assign) BOOL resumeUnityAfterApplicationBecomesActive;
  65. @end
  66. // Internal
  67. @interface UIColor (ALUtils)
  68. + (nullable UIColor *)al_colorWithHexString:(NSString *)hexString;
  69. @end
  70. @interface NSNumber (ALUtils)
  71. + (NSNumber *)al_numberWithString:(NSString *)string;
  72. @end
  73. @interface NSString (ALUtils)
  74. @property (assign, readonly, getter=al_isValidString) BOOL al_validString;
  75. @end
  76. @interface MAAdFormat (ALUtils)
  77. @property (nonatomic, assign, readonly, getter=isFullscreenAd) BOOL fullscreenAd;
  78. @property (nonatomic, assign, readonly, getter=isAdViewAd) BOOL adViewAd;
  79. @end
  80. @implementation MAUnityAdManager
  81. static NSString *const SDK_TAG = @"AppLovinSdk";
  82. static NSString *const TAG = @"MAUnityAdManager";
  83. static NSString *const DEFAULT_AD_VIEW_POSITION = @"top_left";
  84. static ALUnityBackgroundCallback backgroundCallback;
  85. #pragma mark - Initialization
  86. - (instancetype)init
  87. {
  88. self = [super init];
  89. if ( self )
  90. {
  91. self.interstitials = [NSMutableDictionary dictionaryWithCapacity: 2];
  92. self.appOpenAds = [NSMutableDictionary dictionaryWithCapacity: 2];
  93. self.rewardedAds = [NSMutableDictionary dictionaryWithCapacity: 2];
  94. self.adViews = [NSMutableDictionary dictionaryWithCapacity: 2];
  95. self.adViewAdFormats = [NSMutableDictionary dictionaryWithCapacity: 2];
  96. self.adViewPositions = [NSMutableDictionary dictionaryWithCapacity: 2];
  97. self.adViewOffsets = [NSMutableDictionary dictionaryWithCapacity: 2];
  98. self.adViewWidths = [NSMutableDictionary dictionaryWithCapacity: 2];
  99. self.verticalAdViewFormats = [NSMutableDictionary dictionaryWithCapacity: 2];
  100. self.adViewConstraints = [NSMutableDictionary dictionaryWithCapacity: 2];
  101. self.adViewExtraParametersToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1];
  102. self.adViewLocalExtraParametersToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1];
  103. self.adViewCustomDataToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1];
  104. self.adUnitIdentifiersToShowAfterCreate = [NSMutableArray arrayWithCapacity: 2];
  105. self.disabledAdaptiveBannerAdUnitIdentifiers = [NSMutableSet setWithCapacity: 2];
  106. self.disabledAutoRefreshAdViewAdUnitIdentifiers = [NSMutableSet setWithCapacity: 2];
  107. self.ignoreSafeAreaLandscapeAdUnitIdentifiers = [NSMutableSet setWithCapacity: 2];
  108. self.adInfoDict = [NSMutableDictionary dictionary];
  109. self.adInfoDictLock = [[NSObject alloc] init];
  110. self.backgroundCallbackEventsQueue = [[NSOperationQueue alloc] init];
  111. self.backgroundCallbackEventsQueue.maxConcurrentOperationCount = 1;
  112. max_unity_dispatch_on_main_thread(^{
  113. self.safeAreaBackground = [[UIView alloc] init];
  114. self.safeAreaBackground.hidden = YES;
  115. self.safeAreaBackground.backgroundColor = UIColor.clearColor;
  116. self.safeAreaBackground.translatesAutoresizingMaskIntoConstraints = NO;
  117. self.safeAreaBackground.userInteractionEnabled = NO;
  118. UIViewController *rootViewController = [self unityViewController];
  119. [rootViewController.view addSubview: self.safeAreaBackground];
  120. });
  121. // Enable orientation change listener, so that the position can be updated for vertical banners.
  122. [[NSNotificationCenter defaultCenter] addObserverForName: UIDeviceOrientationDidChangeNotification
  123. object: nil
  124. queue: [NSOperationQueue mainQueue]
  125. usingBlock:^(NSNotification *notification) {
  126. for ( NSString *adUnitIdentifier in self.verticalAdViewFormats )
  127. {
  128. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: self.verticalAdViewFormats[adUnitIdentifier]];
  129. }
  130. }];
  131. [[NSNotificationCenter defaultCenter] addObserver: self
  132. selector: @selector(applicationPaused:)
  133. name: UIApplicationDidEnterBackgroundNotification
  134. object: nil];
  135. [[NSNotificationCenter defaultCenter] addObserver: self
  136. selector: @selector(applicationResumed:)
  137. name: UIApplicationDidBecomeActiveNotification
  138. object: nil];
  139. [[NSNotificationCenter defaultCenter] addObserverForName: UIApplicationDidBecomeActiveNotification
  140. object: nil
  141. queue: [NSOperationQueue mainQueue]
  142. usingBlock:^(NSNotification *notification) {
  143. #if !IS_TEST_APP
  144. if ( self.resumeUnityAfterApplicationBecomesActive && UnityIsPaused() )
  145. {
  146. UnityPause(NO);
  147. }
  148. #endif
  149. self.backgroundCallbackEventsQueue.suspended = NO;
  150. }];
  151. }
  152. return self;
  153. }
  154. + (MAUnityAdManager *)shared
  155. {
  156. static dispatch_once_t token;
  157. static MAUnityAdManager *shared;
  158. dispatch_once(&token, ^{
  159. shared = [[MAUnityAdManager alloc] init];
  160. });
  161. return shared;
  162. }
  163. + (void)setUnityBackgroundCallback:(ALUnityBackgroundCallback)unityBackgroundCallback
  164. {
  165. backgroundCallback = unityBackgroundCallback;
  166. }
  167. #pragma mark - Plugin Initialization
  168. - (void)initializeSdkWithConfiguration:(ALSdkInitializationConfiguration *)initConfig andCompletionHandler:(ALSdkInitializationCompletionHandler)completionHandler;
  169. {
  170. self.sdk = [ALSdk shared];
  171. [self.sdk initializeWithConfiguration: initConfig completionHandler:^(ALSdkConfiguration *configuration) {
  172. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  173. // Note: internal state should be updated first
  174. completionHandler( configuration );
  175. NSString *consentFlowUserGeographyStr = @(configuration.consentFlowUserGeography).stringValue;
  176. NSString *consentDialogStateStr = @(configuration.consentDialogState).stringValue;
  177. NSString *appTrackingStatus = @(configuration.appTrackingTransparencyStatus).stringValue; // Deliberately name it `appTrackingStatus` to be a bit more generic (in case Android introduces a similar concept)
  178. [self forwardUnityEventWithArgs: @{@"name" : @"OnSdkInitializedEvent",
  179. @"consentFlowUserGeography" : consentFlowUserGeographyStr,
  180. @"consentDialogState" : consentDialogStateStr,
  181. @"countryCode" : configuration.countryCode,
  182. @"appTrackingStatus" : appTrackingStatus,
  183. @"isSuccessfullyInitialized" : @([self.sdk isInitialized]),
  184. @"isTestModeEnabled" : @([configuration isTestModeEnabled])}];
  185. });
  186. }];
  187. }
  188. #pragma mark - Banners
  189. - (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)bannerPosition isAdaptive:(BOOL)isAdaptive
  190. {
  191. [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] atPosition: bannerPosition withOffset: CGPointZero isAdaptive: isAdaptive];
  192. }
  193. - (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset isAdaptive:(BOOL)isAdaptive
  194. {
  195. [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] atPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) isAdaptive: isAdaptive];
  196. }
  197. - (void)loadBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  198. {
  199. [self loadAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  200. }
  201. - (void)setBannerBackgroundColorForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier hexColorCode:(nullable NSString *)hexColorCode
  202. {
  203. [self setAdViewBackgroundColorForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] hexColorCode: hexColorCode];
  204. }
  205. - (void)setBannerPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  206. {
  207. [self setAdViewPlacement: placement forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  208. }
  209. - (void)startBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  210. {
  211. [self startAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  212. }
  213. - (void)stopBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  214. {
  215. [self stopAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  216. }
  217. - (void)setBannerWidth:(CGFloat)width forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  218. {
  219. [self setAdViewWidth: width forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  220. }
  221. - (void)updateBannerPosition:(nullable NSString *)bannerPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  222. {
  223. [self updateAdViewPosition: bannerPosition withOffset: CGPointZero forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  224. }
  225. - (void)updateBannerPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  226. {
  227. [self updateAdViewPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  228. }
  229. - (void)setBannerExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value
  230. {
  231. [self setAdViewExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] key: key value: value];
  232. }
  233. - (void)setBannerLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value
  234. {
  235. if ( !key )
  236. {
  237. [self log: @"Failed to set local extra parameter: No key specified"];
  238. return;
  239. }
  240. [self setAdViewLocalExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] key: key value: value];
  241. }
  242. - (void)setBannerCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  243. {
  244. [self setAdViewCustomData: customData forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  245. }
  246. - (void)showBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  247. {
  248. [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  249. }
  250. - (void)hideBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  251. {
  252. [self hideAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  253. }
  254. - (NSString *)bannerLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  255. {
  256. return [self adViewLayoutForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  257. }
  258. - (void)destroyBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  259. {
  260. [self destroyAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]];
  261. }
  262. + (CGFloat)adaptiveBannerHeightForWidth:(CGFloat)width
  263. {
  264. return [DEVICE_SPECIFIC_ADVIEW_AD_FORMAT adaptiveSizeForWidth: width].height;
  265. }
  266. #pragma mark - MRECs
  267. - (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)mrecPosition
  268. {
  269. [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec atPosition: mrecPosition withOffset: CGPointZero isAdaptive: NO];
  270. }
  271. - (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset
  272. {
  273. [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec atPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) isAdaptive: NO];
  274. }
  275. - (void)loadMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  276. {
  277. [self loadAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  278. }
  279. - (void)setMRecPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  280. {
  281. [self setAdViewPlacement: placement forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  282. }
  283. - (void)startMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  284. {
  285. [self startAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  286. }
  287. - (void)stopMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  288. {
  289. [self stopAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  290. }
  291. - (void)updateMRecPosition:(nullable NSString *)mrecPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  292. {
  293. [self updateAdViewPosition: mrecPosition withOffset: CGPointZero forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  294. }
  295. - (void)updateMRecPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  296. {
  297. [self updateAdViewPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  298. }
  299. - (void)setMRecExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value
  300. {
  301. [self setAdViewExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec key: key value: value];
  302. }
  303. - (void)setMRecLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value
  304. {
  305. if ( !key )
  306. {
  307. [self log: @"Failed to set local extra parameter: No key specified"];
  308. return;
  309. }
  310. [self setAdViewLocalExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec key: key value: value];
  311. }
  312. - (void)setMRecCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier;
  313. {
  314. [self setAdViewCustomData: customData forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  315. }
  316. - (void)showMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  317. {
  318. [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  319. }
  320. - (void)destroyMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  321. {
  322. [self destroyAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  323. }
  324. - (void)hideMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  325. {
  326. [self hideAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  327. }
  328. - (NSString *)mrecLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  329. {
  330. return [self adViewLayoutForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec];
  331. }
  332. #pragma mark - Interstitials
  333. - (void)loadInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  334. {
  335. MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier];
  336. [interstitial loadAd];
  337. }
  338. - (BOOL)isInterstitialReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  339. {
  340. MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier];
  341. return [interstitial isReady];
  342. }
  343. - (void)showInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData
  344. {
  345. MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier];
  346. [interstitial showAdForPlacement: placement customData: customData];
  347. }
  348. - (void)setInterstitialExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value
  349. {
  350. MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier];
  351. [interstitial setExtraParameterForKey: key value: value];
  352. }
  353. - (void)setInterstitialLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value
  354. {
  355. if ( !key )
  356. {
  357. [self log: @"Failed to set local extra parameter: No key specified"];
  358. return;
  359. }
  360. MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier];
  361. [interstitial setLocalExtraParameterForKey: key value: value];
  362. }
  363. #pragma mark - App Open Ads
  364. - (void)loadAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  365. {
  366. MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier];
  367. [appOpenAd loadAd];
  368. }
  369. - (BOOL)isAppOpenAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  370. {
  371. MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier];
  372. return [appOpenAd isReady];
  373. }
  374. - (void)showAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData
  375. {
  376. MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier];
  377. [appOpenAd showAdForPlacement: placement customData: customData];
  378. }
  379. - (void)setAppOpenAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value
  380. {
  381. MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier];
  382. [appOpenAd setExtraParameterForKey: key value: value];
  383. }
  384. - (void)setAppOpenAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value
  385. {
  386. if ( !key )
  387. {
  388. [self log: @"Failed to set local extra parameter: No key specified"];
  389. return;
  390. }
  391. MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier];
  392. [appOpenAd setLocalExtraParameterForKey: key value: value];
  393. }
  394. #pragma mark - Rewarded
  395. - (void)loadRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  396. {
  397. MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier];
  398. [rewardedAd loadAd];
  399. }
  400. - (BOOL)isRewardedAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier
  401. {
  402. MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier];
  403. return [rewardedAd isReady];
  404. }
  405. - (void)showRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData
  406. {
  407. MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier];
  408. [rewardedAd showAdForPlacement: placement customData: customData];
  409. }
  410. - (void)setRewardedAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value
  411. {
  412. MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier];
  413. [rewardedAd setExtraParameterForKey: key value: value];
  414. }
  415. - (void)setRewardedAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value;
  416. {
  417. if ( !key )
  418. {
  419. [self log: @"Failed to set local extra parameter: No key specified"];
  420. return;
  421. }
  422. MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier];
  423. [rewardedAd setLocalExtraParameterForKey: key value: value];
  424. }
  425. #pragma mark - Event Tracking
  426. - (void)trackEvent:(nullable NSString *)event parameters:(nullable NSString *)parameters
  427. {
  428. NSDictionary<NSString *, id> *deserializedParameters = [MAUnityAdManager deserializeParameters: parameters];
  429. [self.sdk.eventService trackEvent: event parameters: deserializedParameters];
  430. }
  431. #pragma mark - Ad Info
  432. - (NSDictionary<NSString *, id> *)adInfoForAd:(MAAd *)ad
  433. {
  434. return @{@"adUnitId" : ad.adUnitIdentifier,
  435. @"adFormat" : ad.format.label,
  436. @"networkName" : ad.networkName,
  437. @"networkPlacement" : ad.networkPlacement,
  438. @"creativeId" : ad.creativeIdentifier ?: @"",
  439. @"placement" : ad.placement ?: @"",
  440. @"revenue" : [@(ad.revenue) stringValue],
  441. @"revenuePrecision" : ad.revenuePrecision,
  442. @"waterfallInfo" : [self createAdWaterfallInfo: ad.waterfall],
  443. @"latencyMillis" : [self requestLatencyMillisFromRequestLatency: ad.requestLatency],
  444. @"dspName" : ad.DSPName ?: @""};
  445. }
  446. #pragma mark - Waterfall Information
  447. - (NSDictionary<NSString *, id> *)createAdWaterfallInfo:(MAAdWaterfallInfo *)waterfallInfo
  448. {
  449. NSMutableDictionary<NSString *, NSObject *> *waterfallInfoDict = [NSMutableDictionary dictionary];
  450. if ( !waterfallInfo ) return waterfallInfoDict;
  451. waterfallInfoDict[@"name"] = waterfallInfo.name;
  452. waterfallInfoDict[@"testName"] = waterfallInfo.testName;
  453. NSMutableArray<NSDictionary<NSString *, NSObject *> *> *networkResponsesArray = [NSMutableArray arrayWithCapacity: waterfallInfo.networkResponses.count];
  454. for ( MANetworkResponseInfo *response in waterfallInfo.networkResponses )
  455. {
  456. [networkResponsesArray addObject: [self createNetworkResponseInfo: response]];
  457. }
  458. waterfallInfoDict[@"networkResponses"] = networkResponsesArray;
  459. waterfallInfoDict[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: waterfallInfo.latency];
  460. return waterfallInfoDict;
  461. }
  462. - (NSDictionary<NSString *, id> *)createNetworkResponseInfo:(MANetworkResponseInfo *)response
  463. {
  464. NSMutableDictionary<NSString *, NSObject *> *networkResponseDict = [NSMutableDictionary dictionary];
  465. networkResponseDict[@"adLoadState"] = @(response.adLoadState).stringValue;
  466. MAMediatedNetworkInfo *mediatedNetworkInfo = response.mediatedNetwork;
  467. if ( mediatedNetworkInfo )
  468. {
  469. NSMutableDictionary <NSString *, NSObject *> *networkInfoObject = [NSMutableDictionary dictionary];
  470. networkInfoObject[@"name"] = response.mediatedNetwork.name;
  471. networkInfoObject[@"adapterClassName"] = response.mediatedNetwork.adapterClassName;
  472. networkInfoObject[@"adapterVersion"] = response.mediatedNetwork.adapterVersion;
  473. networkInfoObject[@"sdkVersion"] = response.mediatedNetwork.sdkVersion;
  474. networkInfoObject[@"initializationStatus"] = @(response.mediatedNetwork.initializationStatus);
  475. networkResponseDict[@"mediatedNetwork"] = networkInfoObject;
  476. }
  477. networkResponseDict[@"credentials"] = response.credentials;
  478. networkResponseDict[@"isBidding"] = @([response isBidding]);
  479. MAError *error = response.error;
  480. if ( error )
  481. {
  482. NSMutableDictionary<NSString *, NSObject *> *errorObject = [NSMutableDictionary dictionary];
  483. errorObject[@"errorMessage"] = error.message;
  484. errorObject[@"adLoadFailure"] = error.adLoadFailureInfo;
  485. errorObject[@"errorCode"] = @(error.code).stringValue;
  486. errorObject[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: error.requestLatency];
  487. networkResponseDict[@"error"] = errorObject;
  488. }
  489. networkResponseDict[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: response.latency];
  490. return networkResponseDict;
  491. }
  492. #pragma mark - Ad Value
  493. - (NSString *)adValueForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier withKey:(nullable NSString *)key
  494. {
  495. if ( adUnitIdentifier == nil || adUnitIdentifier.length == 0 ) return @"";
  496. if ( key == nil || key.length == 0 ) return @"";
  497. MAAd *ad = [self adWithAdUnitIdentifier: adUnitIdentifier];
  498. if ( !ad ) return @"";
  499. return [ad adValueForKey: key];
  500. }
  501. #pragma mark - Ad Callbacks
  502. - (void)didLoadAd:(MAAd *)ad
  503. {
  504. NSString *name;
  505. MAAdFormat *adFormat = ad.format;
  506. if ( [adFormat isAdViewAd] )
  507. {
  508. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: ad.adUnitIdentifier adFormat: adFormat];
  509. // An ad is now being shown, enable user interaction.
  510. adView.userInteractionEnabled = YES;
  511. if ( MAAdFormat.mrec == adFormat )
  512. {
  513. name = @"OnMRecAdLoadedEvent";
  514. }
  515. else
  516. {
  517. name = @"OnBannerAdLoadedEvent";
  518. }
  519. [self positionAdViewForAd: ad];
  520. // Do not auto-refresh by default if the ad view is not showing yet (e.g. first load during app launch and publisher does not automatically show banner upon load success)
  521. // We will resume auto-refresh in -[MAUnityAdManager showBannerWithAdUnitIdentifier:].
  522. if ( adView && [adView isHidden] )
  523. {
  524. [adView stopAutoRefresh];
  525. }
  526. }
  527. else if ( MAAdFormat.interstitial == adFormat )
  528. {
  529. name = @"OnInterstitialLoadedEvent";
  530. }
  531. else if ( MAAdFormat.appOpen == adFormat )
  532. {
  533. name = @"OnAppOpenAdLoadedEvent";
  534. }
  535. else if ( MAAdFormat.rewarded == adFormat )
  536. {
  537. name = @"OnRewardedAdLoadedEvent";
  538. }
  539. else
  540. {
  541. [self logInvalidAdFormat: adFormat];
  542. return;
  543. }
  544. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  545. @synchronized ( self.adInfoDictLock )
  546. {
  547. self.adInfoDict[ad.adUnitIdentifier] = ad;
  548. }
  549. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  550. [self forwardUnityEventWithArgs: args];
  551. });
  552. }
  553. - (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error
  554. {
  555. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  556. if ( !adUnitIdentifier )
  557. {
  558. [self log: @"adUnitIdentifier cannot be nil from %@", [NSThread callStackSymbols]];
  559. return;
  560. }
  561. NSString *name;
  562. if ( self.adViews[adUnitIdentifier] )
  563. {
  564. MAAdFormat *adFormat = self.adViewAdFormats[adUnitIdentifier];
  565. if ( MAAdFormat.mrec == adFormat )
  566. {
  567. name = @"OnMRecAdLoadFailedEvent";
  568. }
  569. else
  570. {
  571. name = @"OnBannerAdLoadFailedEvent";
  572. }
  573. }
  574. else if ( self.interstitials[adUnitIdentifier] )
  575. {
  576. name = @"OnInterstitialLoadFailedEvent";
  577. }
  578. else if ( self.appOpenAds[adUnitIdentifier] )
  579. {
  580. name = @"OnAppOpenAdLoadFailedEvent";
  581. }
  582. else if ( self.rewardedAds[adUnitIdentifier] )
  583. {
  584. name = @"OnRewardedAdLoadFailedEvent";
  585. }
  586. else
  587. {
  588. [self log: @"invalid adUnitId from %@", [NSThread callStackSymbols]];
  589. return;
  590. }
  591. @synchronized ( self.adInfoDictLock )
  592. {
  593. [self.adInfoDict removeObjectForKey: adUnitIdentifier];
  594. }
  595. [self forwardUnityEventWithArgs: @{@"name" : name,
  596. @"adUnitId" : adUnitIdentifier,
  597. @"errorCode" : [@(error.code) stringValue],
  598. @"errorMessage" : error.message,
  599. @"waterfallInfo" : [self createAdWaterfallInfo: error.waterfall],
  600. @"adLoadFailureInfo" : error.adLoadFailureInfo ?: @"",
  601. @"latencyMillis" : [self requestLatencyMillisFromRequestLatency: error.requestLatency]}];
  602. });
  603. }
  604. - (void)didClickAd:(MAAd *)ad
  605. {
  606. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  607. NSString *name;
  608. MAAdFormat *adFormat = ad.format;
  609. if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat )
  610. {
  611. name = @"OnBannerAdClickedEvent";
  612. }
  613. else if ( MAAdFormat.mrec == adFormat )
  614. {
  615. name = @"OnMRecAdClickedEvent";
  616. }
  617. else if ( MAAdFormat.interstitial == adFormat )
  618. {
  619. name = @"OnInterstitialClickedEvent";
  620. }
  621. else if ( MAAdFormat.appOpen == adFormat )
  622. {
  623. name = @"OnAppOpenAdClickedEvent";
  624. }
  625. else if ( MAAdFormat.rewarded == adFormat )
  626. {
  627. name = @"OnRewardedAdClickedEvent";
  628. }
  629. else
  630. {
  631. [self logInvalidAdFormat: adFormat];
  632. return;
  633. }
  634. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  635. [self forwardUnityEventWithArgs: args];
  636. });
  637. }
  638. - (void)didDisplayAd:(MAAd *)ad
  639. {
  640. // BMLs do not support [DISPLAY] events in Unity
  641. MAAdFormat *adFormat = ad.format;
  642. if ( ![adFormat isFullscreenAd] ) return;
  643. #if !IS_TEST_APP
  644. // UnityPause needs to be called on the main thread.
  645. UnityPause(YES);
  646. #endif
  647. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  648. NSString *name;
  649. if ( MAAdFormat.interstitial == adFormat )
  650. {
  651. name = @"OnInterstitialDisplayedEvent";
  652. }
  653. else if ( MAAdFormat.appOpen == adFormat )
  654. {
  655. name = @"OnAppOpenAdDisplayedEvent";
  656. }
  657. else // rewarded
  658. {
  659. name = @"OnRewardedAdDisplayedEvent";
  660. }
  661. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  662. [self forwardUnityEventWithArgs: args];
  663. });
  664. }
  665. - (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error
  666. {
  667. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  668. // BMLs do not support [DISPLAY] events in Unity
  669. MAAdFormat *adFormat = ad.format;
  670. if ( ![adFormat isFullscreenAd] ) return;
  671. NSString *name;
  672. if ( MAAdFormat.interstitial == adFormat )
  673. {
  674. name = @"OnInterstitialAdFailedToDisplayEvent";
  675. }
  676. else if ( MAAdFormat.appOpen == adFormat )
  677. {
  678. name = @"OnAppOpenAdFailedToDisplayEvent";
  679. }
  680. else // rewarded
  681. {
  682. name = @"OnRewardedAdFailedToDisplayEvent";
  683. }
  684. NSMutableDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  685. args[@"errorCode"] = [@(error.code) stringValue];
  686. args[@"errorMessage"] = error.message;
  687. args[@"mediatedNetworkErrorCode"] = [@(error.mediatedNetworkErrorCode) stringValue];
  688. args[@"mediatedNetworkErrorMessage"] = error.mediatedNetworkErrorMessage;
  689. args[@"waterfallInfo"] = [self createAdWaterfallInfo: error.waterfall];
  690. args[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: error.requestLatency];
  691. [self forwardUnityEventWithArgs: args];
  692. });
  693. }
  694. - (void)didHideAd:(MAAd *)ad
  695. {
  696. // BMLs do not support [HIDDEN] events in Unity
  697. MAAdFormat *adFormat = ad.format;
  698. if ( ![adFormat isFullscreenAd] ) return;
  699. #if !IS_TEST_APP
  700. extern bool _didResignActive;
  701. if ( _didResignActive )
  702. {
  703. // If the application is not active, we should wait until application becomes active to resume unity.
  704. self.resumeUnityAfterApplicationBecomesActive = YES;
  705. }
  706. else
  707. {
  708. // UnityPause needs to be called on the main thread.
  709. UnityPause(NO);
  710. }
  711. #endif
  712. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  713. NSString *name;
  714. if ( MAAdFormat.interstitial == adFormat )
  715. {
  716. name = @"OnInterstitialHiddenEvent";
  717. }
  718. else if ( MAAdFormat.appOpen == adFormat )
  719. {
  720. name = @"OnAppOpenAdHiddenEvent";
  721. }
  722. else // rewarded
  723. {
  724. name = @"OnRewardedAdHiddenEvent";
  725. }
  726. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  727. [self forwardUnityEventWithArgs: args];
  728. });
  729. }
  730. - (void)didExpandAd:(MAAd *)ad
  731. {
  732. MAAdFormat *adFormat = ad.format;
  733. if ( ![adFormat isAdViewAd] )
  734. {
  735. [self logInvalidAdFormat: adFormat];
  736. return;
  737. }
  738. #if !IS_TEST_APP
  739. // UnityPause needs to be called on the main thread.
  740. UnityPause(YES);
  741. #endif
  742. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  743. NSString *name;
  744. if ( MAAdFormat.mrec == adFormat )
  745. {
  746. name = @"OnMRecAdExpandedEvent";
  747. }
  748. else
  749. {
  750. name = @"OnBannerAdExpandedEvent";
  751. }
  752. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  753. [self forwardUnityEventWithArgs: args];
  754. });
  755. }
  756. - (void)didCollapseAd:(MAAd *)ad
  757. {
  758. MAAdFormat *adFormat = ad.format;
  759. if ( ![adFormat isAdViewAd] )
  760. {
  761. [self logInvalidAdFormat: adFormat];
  762. return;
  763. }
  764. #if !IS_TEST_APP
  765. extern bool _didResignActive;
  766. if ( _didResignActive )
  767. {
  768. // If the application is not active, we should wait until application becomes active to resume unity.
  769. self.resumeUnityAfterApplicationBecomesActive = YES;
  770. }
  771. else
  772. {
  773. // UnityPause needs to be called on the main thread.
  774. UnityPause(NO);
  775. }
  776. #endif
  777. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  778. NSString *name;
  779. if ( MAAdFormat.mrec == adFormat )
  780. {
  781. name = @"OnMRecAdCollapsedEvent";
  782. }
  783. else
  784. {
  785. name = @"OnBannerAdCollapsedEvent";
  786. }
  787. NSDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  788. [self forwardUnityEventWithArgs: args];
  789. });
  790. }
  791. - (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward
  792. {
  793. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  794. MAAdFormat *adFormat = ad.format;
  795. if ( adFormat != MAAdFormat.rewarded )
  796. {
  797. [self logInvalidAdFormat: adFormat];
  798. return;
  799. }
  800. NSString *rewardLabel = reward ? reward.label : @"";
  801. NSInteger rewardAmountInt = reward ? reward.amount : 0;
  802. NSString *rewardAmount = [@(rewardAmountInt) stringValue];
  803. NSString *name = @"OnRewardedAdReceivedRewardEvent";
  804. NSMutableDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  805. args[@"rewardLabel"] = rewardLabel;
  806. args[@"rewardAmount"] = rewardAmount;
  807. [self forwardUnityEventWithArgs: args];
  808. });
  809. }
  810. - (void)didPayRevenueForAd:(MAAd *)ad
  811. {
  812. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  813. NSString *name;
  814. MAAdFormat *adFormat = ad.format;
  815. if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat )
  816. {
  817. name = @"OnBannerAdRevenuePaidEvent";
  818. }
  819. else if ( MAAdFormat.mrec == adFormat )
  820. {
  821. name = @"OnMRecAdRevenuePaidEvent";
  822. }
  823. else if ( MAAdFormat.interstitial == adFormat )
  824. {
  825. name = @"OnInterstitialAdRevenuePaidEvent";
  826. }
  827. else if ( MAAdFormat.appOpen == adFormat )
  828. {
  829. name = @"OnAppOpenAdRevenuePaidEvent";
  830. }
  831. else if ( MAAdFormat.rewarded == adFormat )
  832. {
  833. name = @"OnRewardedAdRevenuePaidEvent";
  834. }
  835. else
  836. {
  837. [self logInvalidAdFormat: adFormat];
  838. return;
  839. }
  840. NSMutableDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  841. args[@"keepInBackground"] = @([adFormat isFullscreenAd]);
  842. [self forwardUnityEventWithArgs: args];
  843. });
  844. }
  845. - (void)didReloadExpiredAd:(MAAd *)expiredAd withNewAd:(MAAd *)newAd;
  846. {
  847. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  848. NSString *name;
  849. MAAdFormat *adFormat = newAd.format;
  850. if ( MAAdFormat.interstitial == adFormat )
  851. {
  852. name = @"OnExpiredInterstitialAdReloadedEvent";
  853. }
  854. else if ( MAAdFormat.appOpen == adFormat )
  855. {
  856. name = @"OnExpiredAppOpenAdReloadedEvent";
  857. }
  858. else if ( MAAdFormat.rewarded == adFormat )
  859. {
  860. name = @"OnExpiredRewardedAdReloadedEvent ";
  861. }
  862. else
  863. {
  864. [self logInvalidAdFormat: adFormat];
  865. return;
  866. }
  867. @synchronized ( self.adInfoDictLock )
  868. {
  869. self.adInfoDict[newAd.adUnitIdentifier] = newAd;
  870. }
  871. NSMutableDictionary<NSString *, NSObject *> *args = [NSMutableDictionary dictionary];
  872. args[@"expiredAdInfo"] = [self adInfoForAd: expiredAd];
  873. args[@"newAdInfo"] = [self adInfoForAd: newAd];
  874. args[@"name"] = name;
  875. [self forwardUnityEventWithArgs: args];
  876. });
  877. }
  878. - (void)didGenerateCreativeIdentifier:(NSString *)creativeIdentifier forAd:(MAAd *)ad
  879. {
  880. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  881. NSString *name;
  882. MAAdFormat *adFormat = ad.format;
  883. if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat )
  884. {
  885. name = @"OnBannerAdReviewCreativeIdGeneratedEvent";
  886. }
  887. else if ( MAAdFormat.mrec == adFormat )
  888. {
  889. name = @"OnMRecAdReviewCreativeIdGeneratedEvent";
  890. }
  891. else if ( MAAdFormat.interstitial == adFormat )
  892. {
  893. name = @"OnInterstitialAdReviewCreativeIdGeneratedEvent";
  894. }
  895. else if ( MAAdFormat.rewarded == adFormat )
  896. {
  897. name = @"OnRewardedAdReviewCreativeIdGeneratedEvent";
  898. }
  899. else
  900. {
  901. [self logInvalidAdFormat: adFormat];
  902. return;
  903. }
  904. NSMutableDictionary<NSString *, id> *args = [self defaultAdEventParametersForName: name withAd: ad];
  905. args[@"adReviewCreativeId"] = creativeIdentifier;
  906. args[@"keepInBackground"] = @([adFormat isFullscreenAd]);
  907. // Forward the event in background for fullscreen ads so that the user gets the callback even while the ad is playing.
  908. [self forwardUnityEventWithArgs: args];
  909. });
  910. }
  911. - (NSMutableDictionary<NSString *, id> *)defaultAdEventParametersForName:(NSString *)name withAd:(MAAd *)ad
  912. {
  913. NSMutableDictionary<NSString *, id> *args = [[self adInfoForAd: ad] mutableCopy];
  914. args[@"name"] = name;
  915. return args;
  916. }
  917. #pragma mark - Internal Methods
  918. - (void)createAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat atPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset isAdaptive:(BOOL)isAdaptive
  919. {
  920. max_unity_dispatch_on_main_thread(^{
  921. [self log: @"Creating %@ with ad unit identifier \"%@\" and position: \"%@\"", adFormat, adUnitIdentifier, adViewPosition];
  922. if ( self.adViews[adUnitIdentifier] )
  923. {
  924. [self log: @"Trying to create a %@ that was already created. This will cause the current ad to be hidden.", adFormat.label];
  925. }
  926. // Retrieve ad view from the map
  927. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat atPosition: adViewPosition withOffset: offset isAdaptive: isAdaptive];
  928. adView.hidden = YES;
  929. self.safeAreaBackground.hidden = YES;
  930. // Position ad view immediately so if publisher sets color before ad loads, it will not be the size of the screen
  931. self.adViewAdFormats[adUnitIdentifier] = adFormat;
  932. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  933. NSDictionary<NSString *, NSString *> *extraParameters = self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier];
  934. // Handle initial extra parameters if publisher sets it before creating ad view
  935. if ( extraParameters )
  936. {
  937. for ( NSString *key in extraParameters )
  938. {
  939. [adView setExtraParameterForKey: key value: extraParameters[key]];
  940. [self handleExtraParameterChangesIfNeededForAdUnitIdentifier: adUnitIdentifier
  941. adFormat: adFormat
  942. key: key
  943. value: extraParameters[key]];
  944. }
  945. [self.adViewExtraParametersToSetAfterCreate removeObjectForKey: adUnitIdentifier];
  946. }
  947. // Handle initial local extra parameters if publisher sets it before creating ad view
  948. if ( self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier] )
  949. {
  950. NSDictionary<NSString *, NSString *> *localExtraParameters = self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier];
  951. for ( NSString *key in localExtraParameters )
  952. {
  953. [adView setLocalExtraParameterForKey: key value: localExtraParameters[key]];
  954. }
  955. [self.adViewLocalExtraParametersToSetAfterCreate removeObjectForKey: adUnitIdentifier];
  956. }
  957. // Handle initial custom data if publisher sets it before creating ad view
  958. if ( self.adViewCustomDataToSetAfterCreate[adUnitIdentifier] )
  959. {
  960. NSString *customData = self.adViewCustomDataToSetAfterCreate[adUnitIdentifier];
  961. adView.customData = customData;
  962. [self.adViewCustomDataToSetAfterCreate removeObjectForKey: adUnitIdentifier];
  963. }
  964. [adView loadAd];
  965. // Disable auto-refresh if publisher sets it before creating the ad view.
  966. if ( [self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] )
  967. {
  968. [adView stopAutoRefresh];
  969. }
  970. // The publisher may have requested to show the banner before it was created. Now that the banner is created, show it.
  971. if ( [self.adUnitIdentifiersToShowAfterCreate containsObject: adUnitIdentifier] )
  972. {
  973. [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  974. [self.adUnitIdentifiersToShowAfterCreate removeObject: adUnitIdentifier];
  975. }
  976. });
  977. }
  978. - (void)loadAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  979. {
  980. max_unity_dispatch_on_main_thread(^{
  981. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  982. if ( !adView )
  983. {
  984. [self log: @"%@ does not exist for ad unit identifier \"%@\".", adFormat.label, adUnitIdentifier];
  985. return;
  986. }
  987. if ( ![self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] )
  988. {
  989. if ( [adView isHidden] )
  990. {
  991. [self log: @"Auto-refresh will resume when the %@ ad is shown. You should only call LoadBanner() or LoadMRec() if you explicitly pause auto-refresh and want to manually load an ad.", adFormat.label];
  992. return;
  993. }
  994. [self log: @"You must stop auto-refresh if you want to manually load %@ ads.", adFormat.label];
  995. return;
  996. }
  997. [adView loadAd];
  998. });
  999. }
  1000. - (void)setAdViewBackgroundColorForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat hexColorCode:(NSString *)hexColorCode
  1001. {
  1002. max_unity_dispatch_on_main_thread(^{
  1003. [self log: @"Setting %@ with ad unit identifier \"%@\" to color: \"%@\"", adFormat, adUnitIdentifier, hexColorCode];
  1004. // In some cases, black color may get redrawn on each frame update, resulting in an undesired flicker
  1005. NSString *hexColorCodeToUse = [hexColorCode containsString: @"FF000000"] ? @"FF000001" : hexColorCode;
  1006. UIColor *convertedColor = [UIColor al_colorWithHexString: hexColorCodeToUse];
  1007. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1008. self.publisherBannerBackgroundColor = convertedColor;
  1009. self.safeAreaBackground.backgroundColor = view.backgroundColor = convertedColor;
  1010. // Position adView to ensure logic that depends on background color is properly run
  1011. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1012. });
  1013. }
  1014. - (void)setAdViewPlacement:(nullable NSString *)placement forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1015. {
  1016. max_unity_dispatch_on_main_thread(^{
  1017. [self log: @"Setting placement \"%@\" for \"%@\" with ad unit identifier \"%@\"", placement, adFormat, adUnitIdentifier];
  1018. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1019. adView.placement = placement;
  1020. });
  1021. }
  1022. - (void)startAdViewAutoRefreshForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1023. {
  1024. max_unity_dispatch_on_main_thread(^{
  1025. [self log: @"Starting %@ auto refresh for ad unit identifier \"%@\"", adFormat.label, adUnitIdentifier];
  1026. [self.disabledAutoRefreshAdViewAdUnitIdentifiers removeObject: adUnitIdentifier];
  1027. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1028. if ( !adView )
  1029. {
  1030. [self log: @"%@ does not exist for ad unit identifier %@.", adFormat.label, adUnitIdentifier];
  1031. return;
  1032. }
  1033. [adView startAutoRefresh];
  1034. });
  1035. }
  1036. - (void)stopAdViewAutoRefreshForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1037. {
  1038. max_unity_dispatch_on_main_thread(^{
  1039. [self log: @"Stopping %@ auto refresh for ad unit identifier \"%@\"", adFormat.label, adUnitIdentifier];
  1040. [self.disabledAutoRefreshAdViewAdUnitIdentifiers addObject: adUnitIdentifier];
  1041. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1042. if ( !adView )
  1043. {
  1044. [self log: @"%@ does not exist for ad unit identifier %@.", adFormat.label, adUnitIdentifier];
  1045. return;
  1046. }
  1047. [adView stopAutoRefresh];
  1048. });
  1049. }
  1050. - (void)setAdViewWidth:(CGFloat)width forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1051. {
  1052. max_unity_dispatch_on_main_thread(^{
  1053. [self log: @"Setting width %f for \"%@\" with ad unit identifier \"%@\"", width, adFormat, adUnitIdentifier];
  1054. BOOL isBannerOrLeader = adFormat.isBannerOrLeaderAd;
  1055. // Banners and leaders need to be at least 320pts wide.
  1056. CGFloat minWidth = isBannerOrLeader ? MAAdFormat.banner.size.width : adFormat.size.width;
  1057. if ( width < minWidth )
  1058. {
  1059. [self log: @"The provided width: %f is smaller than the minimum required width: %f for ad format: %@. Automatically setting width to %f.", width, minWidth, adFormat, minWidth];
  1060. }
  1061. CGFloat widthToSet = MAX( minWidth, width );
  1062. self.adViewWidths[adUnitIdentifier] = @(widthToSet);
  1063. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1064. });
  1065. }
  1066. - (void)updateAdViewPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1067. {
  1068. max_unity_dispatch_on_main_thread(^{
  1069. self.adViewPositions[adUnitIdentifier] = adViewPosition;
  1070. self.adViewOffsets[adUnitIdentifier] = [NSValue valueWithCGPoint: offset];
  1071. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1072. });
  1073. }
  1074. - (void)setAdViewExtraParameterForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable NSString *)value
  1075. {
  1076. max_unity_dispatch_on_main_thread(^{
  1077. [self log: @"Setting %@ extra with key: \"%@\" value: \"%@\"", adFormat, key, value];
  1078. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1079. if ( adView )
  1080. {
  1081. [adView setExtraParameterForKey: key value: value];
  1082. }
  1083. else
  1084. {
  1085. [self log: @"%@ does not exist for ad unit identifier \"%@\". Saving extra parameter to be set when it is created.", adFormat, adUnitIdentifier];
  1086. // The adView has not yet been created. Store the extra parameters, so that they can be added once the banner has been created.
  1087. NSMutableDictionary<NSString *, NSString *> *extraParameters = self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier];
  1088. if ( !extraParameters )
  1089. {
  1090. extraParameters = [NSMutableDictionary dictionaryWithCapacity: 1];
  1091. self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier] = extraParameters;
  1092. }
  1093. extraParameters[key] = value;
  1094. }
  1095. // Certain extra parameters need to be handled immediately
  1096. [self handleExtraParameterChangesIfNeededForAdUnitIdentifier: adUnitIdentifier
  1097. adFormat: adFormat
  1098. key: key
  1099. value: value];
  1100. });
  1101. }
  1102. - (void)setAdViewLocalExtraParameterForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable id)value
  1103. {
  1104. max_unity_dispatch_on_main_thread(^{
  1105. [self log: @"Setting %@ local extra with key: \"%@\" value: \"%@\"", adFormat, key, value];
  1106. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1107. if ( adView )
  1108. {
  1109. [adView setLocalExtraParameterForKey: key value: value];
  1110. }
  1111. else
  1112. {
  1113. [self log: @"%@ does not exist for ad unit identifier \"%@\". Saving local extra parameter to be set when it is created.", adFormat, adUnitIdentifier];
  1114. // The adView has not yet been created. Store the loca extra parameters, so that they can be added once the adview has been created.
  1115. NSMutableDictionary<NSString *, id> *localExtraParameters = self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier];
  1116. if ( !localExtraParameters )
  1117. {
  1118. localExtraParameters = [NSMutableDictionary dictionaryWithCapacity: 1];
  1119. self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier] = localExtraParameters;
  1120. }
  1121. localExtraParameters[key] = value;
  1122. }
  1123. });
  1124. }
  1125. - (void)setAdViewCustomData:(nullable NSString *)customData forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1126. {
  1127. max_unity_dispatch_on_main_thread(^{
  1128. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1129. if ( adView )
  1130. {
  1131. adView.customData = customData;
  1132. }
  1133. else
  1134. {
  1135. [self log: @"%@ does not exist for ad unit identifier %@. Saving custom data to be set when it is created.", adFormat, adUnitIdentifier];
  1136. // The adView has not yet been created. Store the custom data, so that they can be added once the AdView has been created.
  1137. self.adViewCustomDataToSetAfterCreate[adUnitIdentifier] = customData;
  1138. }
  1139. });
  1140. }
  1141. - (void)handleExtraParameterChangesIfNeededForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable NSString *)value
  1142. {
  1143. if ( MAAdFormat.mrec != adFormat )
  1144. {
  1145. if ( [@"force_banner" isEqualToString: key] )
  1146. {
  1147. BOOL shouldForceBanner = [NSNumber al_numberWithString: value].boolValue;
  1148. MAAdFormat *forcedAdFormat = shouldForceBanner ? MAAdFormat.banner : DEVICE_SPECIFIC_ADVIEW_AD_FORMAT;
  1149. self.adViewAdFormats[adUnitIdentifier] = forcedAdFormat;
  1150. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: forcedAdFormat];
  1151. }
  1152. else if ( [@"adaptive_banner" isEqualToString: key] )
  1153. {
  1154. [self log: @"Setting adaptive banners via extra parameters is deprecated and will be removed in a future plugin version. Use the CreateBanner(adUnitIdentifier, AdViewConfiguration) API to properly configure adaptive banners."];
  1155. BOOL shouldUseAdaptiveBanner = [NSNumber al_numberWithString: value].boolValue;
  1156. if ( shouldUseAdaptiveBanner )
  1157. {
  1158. [self.disabledAdaptiveBannerAdUnitIdentifiers removeObject: adUnitIdentifier];
  1159. }
  1160. else
  1161. {
  1162. [self.disabledAdaptiveBannerAdUnitIdentifiers addObject: adUnitIdentifier];
  1163. }
  1164. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1165. }
  1166. else if ( [@"ignore_safe_area_landscape" isEqualToString: key] && [NSNumber al_numberWithString: value].boolValue )
  1167. {
  1168. [self.ignoreSafeAreaLandscapeAdUnitIdentifiers addObject: adUnitIdentifier];
  1169. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1170. }
  1171. }
  1172. if ( [adFormat isAdViewAd] && [@"clips_to_bounds" isEqualToString: key] )
  1173. {
  1174. BOOL clipsToBounds = [NSNumber al_numberWithString: value].boolValue;
  1175. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1176. view.clipsToBounds = clipsToBounds;
  1177. }
  1178. }
  1179. - (void)showAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1180. {
  1181. max_unity_dispatch_on_main_thread(^{
  1182. [self log: @"Showing %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier];
  1183. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1184. if ( !view )
  1185. {
  1186. [self log: @"%@ does not exist for ad unit identifier %@.", adFormat, adUnitIdentifier];
  1187. // The adView has not yet been created. Store the ad unit ID, so that it can be displayed once the banner has been created.
  1188. [self.adUnitIdentifiersToShowAfterCreate addObject: adUnitIdentifier];
  1189. }
  1190. else
  1191. {
  1192. // Check edge case where ad may be detatched from view controller
  1193. if ( !view.window.rootViewController )
  1194. {
  1195. [self log: @"%@ missing view controller - re-attaching to %@...", adFormat, [self unityViewController]];
  1196. UIViewController *rootViewController = [self unityViewController];
  1197. [rootViewController.view addSubview: view];
  1198. [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1199. }
  1200. }
  1201. self.safeAreaBackground.hidden = NO;
  1202. view.hidden = NO;
  1203. if ( ![self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] )
  1204. {
  1205. [view startAutoRefresh];
  1206. }
  1207. });
  1208. }
  1209. - (void)hideAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1210. {
  1211. max_unity_dispatch_on_main_thread(^{
  1212. [self log: @"Hiding %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier];
  1213. [self.adUnitIdentifiersToShowAfterCreate removeObject: adUnitIdentifier];
  1214. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1215. view.hidden = YES;
  1216. self.safeAreaBackground.hidden = YES;
  1217. [view stopAutoRefresh];
  1218. });
  1219. }
  1220. - (NSString *)adViewLayoutForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1221. {
  1222. [self log: @"Getting %@ position with ad unit identifier \"%@\"", adFormat, adUnitIdentifier];
  1223. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1224. if ( !view )
  1225. {
  1226. [self log: @"%@ does not exist for ad unit identifier %@", adFormat, adUnitIdentifier];
  1227. return @"";
  1228. }
  1229. CGRect adViewFrame = view.frame;
  1230. return [MAUnityAdManager serializeParameters: @{@"origin_x" : [NSString stringWithFormat: @"%f", adViewFrame.origin.x],
  1231. @"origin_y" : [NSString stringWithFormat: @"%f", adViewFrame.origin.y],
  1232. @"width" : [NSString stringWithFormat: @"%f", CGRectGetWidth(adViewFrame)],
  1233. @"height" : [NSString stringWithFormat: @"%f", CGRectGetHeight(adViewFrame)]}];
  1234. }
  1235. - (void)destroyAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1236. {
  1237. max_unity_dispatch_on_main_thread(^{
  1238. [self log: @"Destroying %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier];
  1239. MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1240. view.delegate = nil;
  1241. view.revenueDelegate = nil;
  1242. view.adReviewDelegate = nil;
  1243. [view removeFromSuperview];
  1244. [self.adViews removeObjectForKey: adUnitIdentifier];
  1245. [self.adViewAdFormats removeObjectForKey: adUnitIdentifier];
  1246. [self.adViewPositions removeObjectForKey: adUnitIdentifier];
  1247. [self.adViewOffsets removeObjectForKey: adUnitIdentifier];
  1248. [self.adViewWidths removeObjectForKey: adUnitIdentifier];
  1249. [self.verticalAdViewFormats removeObjectForKey: adUnitIdentifier];
  1250. [self.disabledAdaptiveBannerAdUnitIdentifiers removeObject: adUnitIdentifier];
  1251. });
  1252. }
  1253. - (void)logInvalidAdFormat:(MAAdFormat *)adFormat
  1254. {
  1255. [self log: @"invalid ad format: %@, from %@", adFormat, [NSThread callStackSymbols]];
  1256. }
  1257. - (void)log:(NSString *)format, ...
  1258. {
  1259. if (max_unity_should_disable_all_logs()) return;
  1260. va_list valist;
  1261. va_start(valist, format);
  1262. NSString *message = [[NSString alloc] initWithFormat: format arguments: valist];
  1263. va_end(valist);
  1264. NSLog(@"[%@] [%@] %@", SDK_TAG, TAG, message);
  1265. }
  1266. + (void)log:(NSString *)format, ...
  1267. {
  1268. if (max_unity_should_disable_all_logs()) return;
  1269. va_list valist;
  1270. va_start(valist, format);
  1271. NSString *message = [[NSString alloc] initWithFormat: format arguments: valist];
  1272. va_end(valist);
  1273. NSLog(@"[%@] [%@] %@", SDK_TAG, TAG, message);
  1274. }
  1275. - (MAInterstitialAd *)retrieveInterstitialForAdUnitIdentifier:(NSString *)adUnitIdentifier
  1276. {
  1277. MAInterstitialAd *result = self.interstitials[adUnitIdentifier];
  1278. if ( !result )
  1279. {
  1280. result = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: adUnitIdentifier];
  1281. result.delegate = self;
  1282. result.revenueDelegate = self;
  1283. result.adReviewDelegate = self;
  1284. result.expirationDelegate = self;
  1285. self.interstitials[adUnitIdentifier] = result;
  1286. }
  1287. return result;
  1288. }
  1289. - (MAAppOpenAd *)retrieveAppOpenAdForAdUnitIdentifier:(NSString *)adUnitIdentifier
  1290. {
  1291. MAAppOpenAd *result = self.appOpenAds[adUnitIdentifier];
  1292. if ( !result )
  1293. {
  1294. result = [[MAAppOpenAd alloc] initWithAdUnitIdentifier: adUnitIdentifier];
  1295. result.delegate = self;
  1296. result.revenueDelegate = self;
  1297. result.expirationDelegate = self;
  1298. self.appOpenAds[adUnitIdentifier] = result;
  1299. }
  1300. return result;
  1301. }
  1302. - (MARewardedAd *)retrieveRewardedAdForAdUnitIdentifier:(NSString *)adUnitIdentifier
  1303. {
  1304. MARewardedAd *result = self.rewardedAds[adUnitIdentifier];
  1305. if ( !result )
  1306. {
  1307. result = [MARewardedAd sharedWithAdUnitIdentifier: adUnitIdentifier];
  1308. result.delegate = self;
  1309. result.revenueDelegate = self;
  1310. result.adReviewDelegate = self;
  1311. result.expirationDelegate = self;
  1312. self.rewardedAds[adUnitIdentifier] = result;
  1313. }
  1314. return result;
  1315. }
  1316. - (MAAdView *)retrieveAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1317. {
  1318. return [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat atPosition: nil withOffset: CGPointZero isAdaptive: YES];
  1319. }
  1320. - (MAAdView *)retrieveAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat atPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset isAdaptive:(BOOL)isAdaptive
  1321. {
  1322. MAAdView *result = self.adViews[adUnitIdentifier];
  1323. if ( !result && adViewPosition )
  1324. {
  1325. MAAdViewConfiguration *config = [MAAdViewConfiguration configurationWithBuilderBlock:^(MAAdViewConfigurationBuilder *builder) {
  1326. // Set adaptive type only for banner ads. If adaptive is enabled, use ANCHORED; otherwise, fall back to NONE.
  1327. if ( [adFormat isBannerOrLeaderAd] )
  1328. {
  1329. if ( isAdaptive )
  1330. {
  1331. builder.adaptiveType = MAAdViewAdaptiveTypeAnchored;
  1332. }
  1333. else
  1334. {
  1335. builder.adaptiveType = MAAdViewAdaptiveTypeNone;
  1336. [self.disabledAdaptiveBannerAdUnitIdentifiers addObject:adUnitIdentifier];
  1337. }
  1338. }
  1339. }];
  1340. // There is a Unity bug where if an empty UIView is on screen with user interaction enabled, and a user interacts with it, it just passes the events to random parts of the screen.
  1341. result = [[MAAdView alloc] initWithAdUnitIdentifier:adUnitIdentifier adFormat:adFormat configuration:config];
  1342. result.userInteractionEnabled = NO;
  1343. result.translatesAutoresizingMaskIntoConstraints = NO;
  1344. result.delegate = self;
  1345. result.revenueDelegate = self;
  1346. result.adReviewDelegate = self;
  1347. self.adViews[adUnitIdentifier] = result;
  1348. self.adViewPositions[adUnitIdentifier] = adViewPosition;
  1349. self.adViewOffsets[adUnitIdentifier] = [NSValue valueWithCGPoint: offset];
  1350. UIViewController *rootViewController = [self unityViewController];
  1351. [rootViewController.view addSubview: result];
  1352. // Allow pubs to pause auto-refresh immediately, by default.
  1353. [result setExtraParameterForKey: @"allow_pause_auto_refresh_immediately" value: @"true"];
  1354. }
  1355. return result;
  1356. }
  1357. - (void)positionAdViewForAd:(MAAd *)ad
  1358. {
  1359. [self positionAdViewForAdUnitIdentifier: ad.adUnitIdentifier adFormat: ad.format];
  1360. }
  1361. - (void)positionAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat
  1362. {
  1363. max_unity_dispatch_on_main_thread(^{
  1364. MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat];
  1365. NSString *adViewPosition = self.adViewPositions[adUnitIdentifier];
  1366. NSValue *adViewPositionValue = self.adViewOffsets[adUnitIdentifier];
  1367. CGPoint adViewOffset = [adViewPositionValue CGPointValue];
  1368. BOOL isAdaptiveBannerDisabled = [self.disabledAdaptiveBannerAdUnitIdentifiers containsObject: adUnitIdentifier];
  1369. BOOL isWidthPtsOverridden = self.adViewWidths[adUnitIdentifier] != nil;
  1370. UIView *superview = adView.superview;
  1371. if ( !superview ) return;
  1372. // Deactivate any previous constraints and reset rotation so that the banner can be positioned again.
  1373. NSArray<NSLayoutConstraint *> *activeConstraints = self.adViewConstraints[adUnitIdentifier];
  1374. [NSLayoutConstraint deactivateConstraints: activeConstraints];
  1375. adView.transform = CGAffineTransformIdentity;
  1376. [self.verticalAdViewFormats removeObjectForKey: adUnitIdentifier];
  1377. // Ensure superview contains the safe area background.
  1378. if ( ![superview.subviews containsObject: self.safeAreaBackground] )
  1379. {
  1380. [self.safeAreaBackground removeFromSuperview];
  1381. [superview insertSubview: self.safeAreaBackground belowSubview: adView];
  1382. }
  1383. // Deactivate any previous constraints and reset visibility state so that the safe area background can be positioned again.
  1384. [NSLayoutConstraint deactivateConstraints: self.safeAreaBackground.constraints];
  1385. self.safeAreaBackground.hidden = adView.hidden;
  1386. //
  1387. // Determine ad width
  1388. //
  1389. CGFloat adViewWidth;
  1390. // Check if publisher has overridden width as points
  1391. if ( isWidthPtsOverridden )
  1392. {
  1393. adViewWidth = self.adViewWidths[adUnitIdentifier].floatValue;
  1394. }
  1395. // Top center / bottom center stretches full screen
  1396. else if ( [adViewPosition isEqual: @"top_center"] || [adViewPosition isEqual: @"bottom_center"] )
  1397. {
  1398. adViewWidth = CGRectGetWidth(KEY_WINDOW.bounds);
  1399. }
  1400. // Else use standard widths of 320, 728, or 300
  1401. else
  1402. {
  1403. adViewWidth = adFormat.size.width;
  1404. }
  1405. //
  1406. // Determine ad height
  1407. //
  1408. CGFloat adViewHeight;
  1409. if ( (adFormat == MAAdFormat.banner || adFormat == MAAdFormat.leader) && !isAdaptiveBannerDisabled )
  1410. {
  1411. adViewHeight = [adFormat adaptiveSizeForWidth: adViewWidth].height;
  1412. }
  1413. else
  1414. {
  1415. adViewHeight = adFormat.size.height;
  1416. }
  1417. CGSize adViewSize = CGSizeMake(adViewWidth, adViewHeight);
  1418. // All positions have constant height
  1419. NSMutableArray<NSLayoutConstraint *> *constraints = [NSMutableArray arrayWithObject: [adView.heightAnchor constraintEqualToConstant: adViewSize.height]];
  1420. UILayoutGuide *layoutGuide = superview.safeAreaLayoutGuide;
  1421. BOOL shouldIgnoreSafeArea = [self shouldIgnoreSafeAreaForAdUnitIdentifier: adUnitIdentifier];
  1422. NSLayoutAnchor *topAnchor = shouldIgnoreSafeArea ? superview.topAnchor : layoutGuide.topAnchor;
  1423. if ( [adViewPosition isEqual: @"top_center"] || [adViewPosition isEqual: @"bottom_center"] )
  1424. {
  1425. // Non AdMob banners will still be of 50/90 points tall. Set the auto sizing mask such that the inner ad view is pinned to the bottom or top according to the ad view position.
  1426. if ( !isAdaptiveBannerDisabled )
  1427. {
  1428. adView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1429. if ( [@"top_center" isEqual: adViewPosition] )
  1430. {
  1431. adView.autoresizingMask |= UIViewAutoresizingFlexibleBottomMargin;
  1432. }
  1433. else // bottom_center
  1434. {
  1435. adView.autoresizingMask |= UIViewAutoresizingFlexibleTopMargin;
  1436. }
  1437. }
  1438. // If publisher actually provided a banner background color
  1439. if ( self.publisherBannerBackgroundColor && adFormat != MAAdFormat.mrec )
  1440. {
  1441. if ( isWidthPtsOverridden )
  1442. {
  1443. [constraints addObjectsFromArray: @[[adView.widthAnchor constraintEqualToConstant: adViewWidth],
  1444. [adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor],
  1445. [self.safeAreaBackground.widthAnchor constraintEqualToConstant: adViewWidth],
  1446. [self.safeAreaBackground.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor]]];
  1447. if ( [adViewPosition isEqual: @"top_center"] )
  1448. {
  1449. [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: topAnchor],
  1450. [self.safeAreaBackground.topAnchor constraintEqualToAnchor: superview.topAnchor],
  1451. [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: adView.topAnchor]]];
  1452. }
  1453. else // bottom_center
  1454. {
  1455. [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor],
  1456. [self.safeAreaBackground.topAnchor constraintEqualToAnchor: adView.bottomAnchor],
  1457. [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: superview.bottomAnchor]]];
  1458. }
  1459. }
  1460. else
  1461. {
  1462. [constraints addObjectsFromArray: @[[adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor],
  1463. [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor],
  1464. [self.safeAreaBackground.leftAnchor constraintEqualToAnchor: superview.leftAnchor],
  1465. [self.safeAreaBackground.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]];
  1466. if ( [adViewPosition isEqual: @"top_center"] )
  1467. {
  1468. [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: topAnchor],
  1469. [self.safeAreaBackground.topAnchor constraintEqualToAnchor: superview.topAnchor],
  1470. [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: adView.topAnchor]]];
  1471. }
  1472. else // bottom_center
  1473. {
  1474. [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor],
  1475. [self.safeAreaBackground.topAnchor constraintEqualToAnchor: adView.bottomAnchor],
  1476. [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: superview.bottomAnchor]]];
  1477. }
  1478. }
  1479. }
  1480. // If pub does not have a background color set or this is not a banner
  1481. else
  1482. {
  1483. self.safeAreaBackground.hidden = YES;
  1484. [constraints addObjectsFromArray: @[[adView.widthAnchor constraintEqualToConstant: adViewWidth],
  1485. [adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor]]];
  1486. if ( [adViewPosition isEqual: @"top_center"] )
  1487. {
  1488. [constraints addObject: [adView.topAnchor constraintEqualToAnchor: topAnchor]];
  1489. }
  1490. else // BottomCenter
  1491. {
  1492. [constraints addObject: [adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor]];
  1493. }
  1494. }
  1495. }
  1496. // Check if the publisher wants vertical banners.
  1497. else if ( [adViewPosition isEqual: @"center_left"] || [adViewPosition isEqual: @"center_right"] )
  1498. {
  1499. if ( MAAdFormat.mrec == adFormat )
  1500. {
  1501. [constraints addObject: [adView.widthAnchor constraintEqualToConstant: adViewSize.width]];
  1502. if ( [adViewPosition isEqual: @"center_left"] )
  1503. {
  1504. [constraints addObjectsFromArray: @[[adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor],
  1505. [adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]];
  1506. [constraints addObjectsFromArray: @[[self.safeAreaBackground.rightAnchor constraintEqualToAnchor: layoutGuide.leftAnchor],
  1507. [self.safeAreaBackground.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]];
  1508. }
  1509. else // center_right
  1510. {
  1511. [constraints addObjectsFromArray: @[[adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor],
  1512. [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]];
  1513. [constraints addObjectsFromArray: @[[self.safeAreaBackground.leftAnchor constraintEqualToAnchor: layoutGuide.rightAnchor],
  1514. [self.safeAreaBackground.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]];
  1515. }
  1516. }
  1517. else
  1518. {
  1519. /* Align the center of the view such that when rotated it snaps into place.
  1520. *
  1521. * +---+---+-------+
  1522. * | | |
  1523. * | | |
  1524. * | | |
  1525. * | | |
  1526. * | | |
  1527. * | | |
  1528. * +-------------+---+-----------+--+
  1529. * | | + | + | |
  1530. * +-------------+---+-----------+--+
  1531. * <+> | |
  1532. * |+ | |
  1533. * || | |
  1534. * || | |
  1535. * || | |
  1536. * || | |
  1537. * +|--+-----------+
  1538. * v
  1539. * Banner Half Height
  1540. */
  1541. self.safeAreaBackground.hidden = YES;
  1542. adView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2);
  1543. CGFloat width;
  1544. // If the publiser has a background color set - set the width to the height of the screen, to span the ad across the screen after it is rotated.
  1545. if ( self.publisherBannerBackgroundColor )
  1546. {
  1547. if ( isWidthPtsOverridden )
  1548. {
  1549. width = adViewWidth;
  1550. }
  1551. else
  1552. {
  1553. width = CGRectGetHeight(KEY_WINDOW.bounds);
  1554. }
  1555. }
  1556. // Otherwise - we shouldn't span the banner the width of the realm (there might be user-interactable UI on the sides)
  1557. else
  1558. {
  1559. width = adViewWidth;
  1560. }
  1561. [constraints addObject: [adView.widthAnchor constraintEqualToConstant: width]];
  1562. // Set constraints such that the center of the banner aligns with the center left or right as needed. That way, once rotated, the banner snaps into place.
  1563. [constraints addObject: [adView.centerYAnchor constraintEqualToAnchor: superview.centerYAnchor]];
  1564. // Place the center of the banner half the height of the banner away from the side. If we align the center exactly with the left/right anchor, only half the banner will be visible.
  1565. CGFloat bannerHalfHeight = adViewSize.height / 2.0;
  1566. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  1567. if ( [adViewPosition isEqual: @"center_left"] )
  1568. {
  1569. NSLayoutAnchor *anchor = ( orientation == UIInterfaceOrientationLandscapeRight ) ? layoutGuide.leftAnchor : superview.leftAnchor;
  1570. [constraints addObject: [adView.centerXAnchor constraintEqualToAnchor: anchor constant: bannerHalfHeight]];
  1571. }
  1572. else // CenterRight
  1573. {
  1574. NSLayoutAnchor *anchor = ( orientation == UIInterfaceOrientationLandscapeLeft ) ? layoutGuide.rightAnchor : superview.rightAnchor;
  1575. [constraints addObject: [adView.centerXAnchor constraintEqualToAnchor: anchor constant: -bannerHalfHeight]];
  1576. }
  1577. // Store the ad view with format, so that it can be updated when the orientation changes.
  1578. self.verticalAdViewFormats[adUnitIdentifier] = adFormat;
  1579. // If adaptive - make top flexible since we anchor with the bottom of the banner at the edge of the screen
  1580. if ( !isAdaptiveBannerDisabled )
  1581. {
  1582. adView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
  1583. }
  1584. }
  1585. }
  1586. // Otherwise, publisher will likely construct his own views around the adview
  1587. else
  1588. {
  1589. self.safeAreaBackground.hidden = YES;
  1590. [constraints addObject: [adView.widthAnchor constraintEqualToConstant: adViewWidth]];
  1591. if ( [adViewPosition isEqual: @"top_left"] )
  1592. {
  1593. [constraints addObjectsFromArray: @[[adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor constant: adViewOffset.x],
  1594. [adView.topAnchor constraintEqualToAnchor: topAnchor constant: adViewOffset.y]]];
  1595. }
  1596. else if ( [adViewPosition isEqual: @"top_right"] )
  1597. {
  1598. [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: topAnchor],
  1599. [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]];
  1600. }
  1601. else if ( [adViewPosition isEqual: @"centered"] )
  1602. {
  1603. [constraints addObjectsFromArray: @[[adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor],
  1604. [adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor]]];
  1605. }
  1606. else if ( [adViewPosition isEqual: @"bottom_left"] )
  1607. {
  1608. [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor],
  1609. [adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]];
  1610. }
  1611. else if ( [adViewPosition isEqual: @"bottom_right"] )
  1612. {
  1613. [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor],
  1614. [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]];
  1615. }
  1616. }
  1617. self.adViewConstraints[adUnitIdentifier] = constraints;
  1618. [NSLayoutConstraint activateConstraints: constraints];
  1619. });
  1620. }
  1621. - (UIViewController *)unityViewController
  1622. {
  1623. // Handle edge case where `UnityGetGLViewController()` returns nil
  1624. return UnityGetGLViewController() ?: UnityGetMainWindow().rootViewController ?: [KEY_WINDOW rootViewController];
  1625. }
  1626. - (void)forwardUnityEventWithArgs:(NSDictionary<NSString *, id> *)args
  1627. {
  1628. #if !IS_TEST_APP
  1629. extern bool _didResignActive;
  1630. // We should not call any script callbacks when application is not active. Suspend the callback queue if resign is active.
  1631. // We'll resume the queue once the application becomes active again.
  1632. self.backgroundCallbackEventsQueue.suspended = _didResignActive;
  1633. #endif
  1634. [self.backgroundCallbackEventsQueue addOperationWithBlock:^{
  1635. NSString *serializedParameters = [MAUnityAdManager serializeParameters: args];
  1636. backgroundCallback(serializedParameters.UTF8String);
  1637. }];
  1638. }
  1639. + (NSString *)serializeParameters:(NSDictionary<NSString *, id> *)dict
  1640. {
  1641. NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict options: 0 error: nil];
  1642. return [[NSString alloc] initWithData: jsonData encoding: NSUTF8StringEncoding];
  1643. }
  1644. + (NSDictionary<NSString *, id> *)deserializeParameters:(nullable NSString *)serialized
  1645. {
  1646. if ( serialized.length > 0 )
  1647. {
  1648. NSError *error;
  1649. NSDictionary<NSString *, id> *deserialized = [NSJSONSerialization JSONObjectWithData: [serialized dataUsingEncoding:NSUTF8StringEncoding]
  1650. options: 0
  1651. error: &error];
  1652. if ( error )
  1653. {
  1654. [self log: @"Failed to deserialize (%@) with error %@", serialized, error];
  1655. return @{};
  1656. }
  1657. return deserialized;
  1658. }
  1659. else
  1660. {
  1661. return @{};
  1662. }
  1663. }
  1664. - (MAAdFormat *)adViewAdFormatForAdUnitIdentifier:(NSString *)adUnitIdentifier
  1665. {
  1666. if ( self.adViewAdFormats[adUnitIdentifier] )
  1667. {
  1668. return self.adViewAdFormats[adUnitIdentifier];
  1669. }
  1670. else
  1671. {
  1672. return DEVICE_SPECIFIC_ADVIEW_AD_FORMAT;
  1673. }
  1674. }
  1675. - (NSString *)requestLatencyMillisFromRequestLatency:(NSTimeInterval)requestLatency
  1676. {
  1677. // Convert latency from seconds to milliseconds to match Android.
  1678. long requestLatencyMillis = requestLatency * 1000;
  1679. return @(requestLatencyMillis).stringValue;
  1680. }
  1681. #pragma mark - User Service
  1682. - (void)didDismissUserConsentDialog
  1683. {
  1684. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1685. [self forwardUnityEventWithArgs: @{@"name" : @"OnSdkConsentDialogDismissedEvent"}];
  1686. });
  1687. }
  1688. #pragma mark - CMP Service
  1689. - (void)showCMPForExistingUser
  1690. {
  1691. [self.sdk.cmpService showCMPForExistingUserWithCompletion:^(ALCMPError * _Nullable error) {
  1692. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1693. NSMutableDictionary<NSString *, id> *args = [NSMutableDictionary dictionaryWithCapacity: 2];
  1694. args[@"name"] = @"OnCmpCompletedEvent";
  1695. if ( error )
  1696. {
  1697. args[@"error"] = @{@"code": @(error.code),
  1698. @"message": error.message,
  1699. @"cmpCode": @(error.cmpCode),
  1700. @"cmpMessage": error.cmpMessage,
  1701. @"keepInBackground": @(YES)};
  1702. }
  1703. [self forwardUnityEventWithArgs: args];
  1704. });
  1705. }];
  1706. }
  1707. #pragma mark - Application
  1708. - (void)applicationPaused:(NSNotification *)notification
  1709. {
  1710. [self notifyApplicationStateChangedEventForPauseState: YES];
  1711. }
  1712. - (void)applicationResumed:(NSNotification *)notification
  1713. {
  1714. [self notifyApplicationStateChangedEventForPauseState: NO];
  1715. }
  1716. - (void)notifyApplicationStateChangedEventForPauseState:(BOOL)isPaused
  1717. {
  1718. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1719. [self forwardUnityEventWithArgs: @{@"name": @"OnApplicationStateChanged",
  1720. @"isPaused": @(isPaused)}];
  1721. });
  1722. }
  1723. - (MAAd *)adWithAdUnitIdentifier:(NSString *)adUnitIdentifier
  1724. {
  1725. @synchronized ( self.adInfoDictLock )
  1726. {
  1727. return self.adInfoDict[adUnitIdentifier];
  1728. }
  1729. }
  1730. #pragma mark - Helper
  1731. - (BOOL)shouldIgnoreSafeAreaForAdUnitIdentifier:(NSString *)adUnitIdentifier
  1732. {
  1733. if ( ![self.ignoreSafeAreaLandscapeAdUnitIdentifiers containsObject: adUnitIdentifier] ) return NO;
  1734. // We should use the superview instead of layout guide if the application's orientation is landscape and the extra parameter is set
  1735. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  1736. return orientation == UIInterfaceOrientationLandscapeRight || orientation == UIInterfaceOrientationLandscapeLeft;
  1737. }
  1738. @end