FIRIAMDisplayExecutor.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <TargetConditionals.h>
  17. #if TARGET_OS_IOS || TARGET_OS_TV
  18. #import <UIKit/UIKit.h>
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseInAppMessaging/Sources/FIRCore+InAppMessaging.h"
  21. #import "FirebaseInAppMessaging/Sources/Private/Data/FIRIAMMessageContentData.h"
  22. #import "FirebaseInAppMessaging/Sources/Private/Data/FIRIAMMessageDefinition.h"
  23. #import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMActivityLogger.h"
  24. #import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMDisplayExecutor.h"
  25. #import "FirebaseInAppMessaging/Sources/Public/FirebaseInAppMessaging/FIRInAppMessaging.h"
  26. #import "FirebaseInAppMessaging/Sources/RenderingObjects/FIRInAppMessagingRenderingPrivate.h"
  27. #import "FirebaseInAppMessaging/Sources/Runtime/FIRIAMSDKRuntimeErrorCodes.h"
  28. #import "FirebaseABTesting/Sources/Private/FirebaseABTestingInternal.h"
  29. @implementation FIRIAMDisplaySetting
  30. @end
  31. @interface FIRIAMDisplayExecutor () <FIRInAppMessagingDisplayDelegate>
  32. @property(nonatomic) id<FIRIAMTimeFetcher> timeFetcher;
  33. // YES if a message is being rendered at this time
  34. @property(nonatomic) BOOL isMsgBeingDisplayed;
  35. @property(nonatomic) NSTimeInterval lastDisplayTime;
  36. @property(nonatomic, nonnull, readonly) FIRInAppMessaging *inAppMessaging;
  37. @property(nonatomic, nonnull, readonly) FIRIAMDisplaySetting *setting;
  38. @property(nonatomic, nonnull, readonly) FIRIAMMessageClientCache *messageCache;
  39. @property(nonatomic, nonnull, readonly) id<FIRIAMBookKeeper> displayBookKeeper;
  40. @property(nonatomic) BOOL impressionRecorded;
  41. @property(nonatomic, nonnull, readonly) id<FIRIAMAnalyticsEventLogger> analyticsEventLogger;
  42. @property(nonatomic, nonnull, readonly) FIRIAMActionURLFollower *actionURLFollower;
  43. // Used for displaying the test on device message error alert.
  44. @property(nonatomic, strong) UIWindow *alertWindow;
  45. @end
  46. @implementation FIRIAMDisplayExecutor {
  47. FIRIAMMessageDefinition *_currentMsgBeingDisplayed;
  48. }
  49. + (NSString *)logStringForNilMessageDisplayComponent {
  50. #if TARGET_OS_IOS
  51. return @"Message display component is not present yet. No display should happen.";
  52. #else // TARGET_OS_TV
  53. return @"There is no default UI for tvOS. You must implement a messageDisplayComponent and set "
  54. @"it on the InAppMessaging singleton. See "
  55. @"https://firebase.google.com/docs/in-app-messaging/"
  56. @"customize-messages#create_your_own_message_display_library.";
  57. #endif
  58. }
  59. #pragma mark - FIRInAppMessagingDisplayDelegate methods
  60. - (void)messageClicked:(FIRInAppMessagingDisplayMessage *)inAppMessage
  61. withAction:(FIRInAppMessagingAction *)action {
  62. // Call through to app-side delegate.
  63. __weak id<FIRInAppMessagingDisplayDelegate> appSideDelegate = self.inAppMessaging.delegate;
  64. if ([appSideDelegate respondsToSelector:@selector(messageClicked:withAction:)]) {
  65. [appSideDelegate messageClicked:inAppMessage withAction:action];
  66. }
  67. self.isMsgBeingDisplayed = NO;
  68. if (!_currentMsgBeingDisplayed.renderData.messageID) {
  69. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM400030",
  70. @"messageClicked called but "
  71. "there is no current message ID.");
  72. return;
  73. }
  74. if (_currentMsgBeingDisplayed.isTestMessage) {
  75. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400031",
  76. @"A test message clicked. Do test event impression/click analytics logging");
  77. [self.analyticsEventLogger
  78. logAnalyticsEventForType:FIRIAMAnalyticsEventTestMessageImpression
  79. forCampaignID:_currentMsgBeingDisplayed.renderData.messageID
  80. withCampaignName:_currentMsgBeingDisplayed.renderData.name
  81. eventTimeInMs:nil
  82. completion:^(BOOL success) {
  83. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400036",
  84. @"Logging analytics event for url following %@",
  85. success ? @"succeeded" : @"failed");
  86. }];
  87. [self.analyticsEventLogger
  88. logAnalyticsEventForType:FIRIAMAnalyticsEventTestMessageClick
  89. forCampaignID:_currentMsgBeingDisplayed.renderData.messageID
  90. withCampaignName:_currentMsgBeingDisplayed.renderData.name
  91. eventTimeInMs:nil
  92. completion:^(BOOL success) {
  93. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400039",
  94. @"Logging analytics event for url following %@",
  95. success ? @"succeeded" : @"failed");
  96. }];
  97. } else {
  98. // Logging the impression
  99. [self recordValidImpression:_currentMsgBeingDisplayed.renderData.messageID
  100. withMessageName:_currentMsgBeingDisplayed.renderData.name];
  101. if (action.actionURL) {
  102. [self.analyticsEventLogger
  103. logAnalyticsEventForType:FIRIAMAnalyticsEventActionURLFollow
  104. forCampaignID:_currentMsgBeingDisplayed.renderData.messageID
  105. withCampaignName:_currentMsgBeingDisplayed.renderData.name
  106. eventTimeInMs:nil
  107. completion:^(BOOL success) {
  108. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400032",
  109. @"Logging analytics event for url following %@",
  110. success ? @"succeeded" : @"failed");
  111. }];
  112. // Also start tracking conversions.
  113. [self.analyticsEventLogger
  114. logConversionTrackingEventForCampaignID:_currentMsgBeingDisplayed.renderData.messageID];
  115. }
  116. }
  117. NSURL *actionURL = action.actionURL;
  118. if (!actionURL) {
  119. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400033",
  120. @"messageClicked called but "
  121. "there is no action url specified in the message data.");
  122. // it's equivalent to closing the message with no further action
  123. return;
  124. } else {
  125. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400037", @"Following action url %@",
  126. actionURL.absoluteString);
  127. @try {
  128. [self.actionURLFollower
  129. followActionURL:actionURL
  130. withCompletionBlock:^(BOOL success) {
  131. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400034",
  132. @"Seeing %@ from following action URL", success ? @"success" : @"error");
  133. }];
  134. } @catch (NSException *e) {
  135. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM400035",
  136. @"Exception encountered in following "
  137. "action url (%@): %@ ",
  138. actionURL, e.description);
  139. @throw;
  140. }
  141. }
  142. }
  143. - (void)messageDismissed:(FIRInAppMessagingDisplayMessage *)inAppMessage
  144. dismissType:(FIRInAppMessagingDismissType)dismissType {
  145. // Call through to app-side delegate.
  146. __weak id<FIRInAppMessagingDisplayDelegate> appSideDelegate = self.inAppMessaging.delegate;
  147. if ([appSideDelegate respondsToSelector:@selector(messageDismissed:dismissType:)]) {
  148. [appSideDelegate messageDismissed:inAppMessage dismissType:dismissType];
  149. }
  150. self.isMsgBeingDisplayed = NO;
  151. if (!_currentMsgBeingDisplayed.renderData.messageID) {
  152. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM400014",
  153. @"messageDismissedWithType called but "
  154. "there is no current message ID.");
  155. return;
  156. }
  157. if (_currentMsgBeingDisplayed.isTestMessage) {
  158. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400020",
  159. @"A test message dismissed. Record the impression event.");
  160. [self.analyticsEventLogger
  161. logAnalyticsEventForType:FIRIAMAnalyticsEventTestMessageImpression
  162. forCampaignID:_currentMsgBeingDisplayed.renderData.messageID
  163. withCampaignName:_currentMsgBeingDisplayed.renderData.name
  164. eventTimeInMs:nil
  165. completion:^(BOOL success) {
  166. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400038",
  167. @"Logging analytics event for url following %@",
  168. success ? @"succeeded" : @"failed");
  169. }];
  170. return;
  171. }
  172. // Logging the impression
  173. [self recordValidImpression:_currentMsgBeingDisplayed.renderData.messageID
  174. withMessageName:_currentMsgBeingDisplayed.renderData.name];
  175. FIRIAMAnalyticsLogEventType logEventType = dismissType == FIRInAppMessagingDismissTypeAuto
  176. ? FIRIAMAnalyticsEventMessageDismissAuto
  177. : FIRIAMAnalyticsEventMessageDismissClick;
  178. [self.analyticsEventLogger
  179. logAnalyticsEventForType:logEventType
  180. forCampaignID:_currentMsgBeingDisplayed.renderData.messageID
  181. withCampaignName:_currentMsgBeingDisplayed.renderData.name
  182. eventTimeInMs:nil
  183. completion:^(BOOL success) {
  184. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400004",
  185. @"Logging analytics event for message dismiss %@",
  186. success ? @"succeeded" : @"failed");
  187. }];
  188. }
  189. - (void)impressionDetectedForMessage:(FIRInAppMessagingDisplayMessage *)inAppMessage {
  190. __weak id<FIRInAppMessagingDisplayDelegate> appSideDelegate = self.inAppMessaging.delegate;
  191. if ([appSideDelegate respondsToSelector:@selector(impressionDetectedForMessage:)]) {
  192. [appSideDelegate impressionDetectedForMessage:inAppMessage];
  193. }
  194. if (!_currentMsgBeingDisplayed.renderData.messageID) {
  195. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM400022",
  196. @"impressionDetected called but "
  197. "there is no current message ID.");
  198. return;
  199. }
  200. // If this is an experimental FIAM, activate the experiment.
  201. if (inAppMessage.campaignInfo.experimentPayload) {
  202. [[FIRExperimentController sharedInstance]
  203. activateExperiment:inAppMessage.campaignInfo.experimentPayload
  204. forServiceOrigin:@"fiam"];
  205. }
  206. if (!_currentMsgBeingDisplayed.isTestMessage) {
  207. // Displayed long enough to be a valid impression.
  208. [self recordValidImpression:_currentMsgBeingDisplayed.renderData.messageID
  209. withMessageName:_currentMsgBeingDisplayed.renderData.name];
  210. if ([self shouldTrackConversionsOnImpressionForCurrentInAppMessage:_currentMsgBeingDisplayed]) {
  211. [self.analyticsEventLogger
  212. logConversionTrackingEventForCampaignID:_currentMsgBeingDisplayed.renderData.messageID];
  213. }
  214. } else {
  215. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400011",
  216. @"A test message. Record the test message impression event.");
  217. return;
  218. }
  219. }
  220. - (BOOL)shouldTrackConversionsOnImpressionForCurrentInAppMessage:
  221. (FIRIAMMessageDefinition *)inAppMessage {
  222. // If the message has no action URL, an impression is enough to start tracking conversions.
  223. id<FIRIAMMessageContentData> contentData = inAppMessage.renderData.contentData;
  224. return contentData.actionURL == nil && contentData.secondaryActionURL == nil;
  225. }
  226. - (void)displayErrorForMessage:(FIRInAppMessagingDisplayMessage *)inAppMessage
  227. error:(NSError *)error {
  228. __weak id<FIRInAppMessagingDisplayDelegate> appSideDelegate = self.inAppMessaging.delegate;
  229. if ([appSideDelegate respondsToSelector:@selector(displayErrorForMessage:error:)]) {
  230. [appSideDelegate displayErrorForMessage:inAppMessage error:error];
  231. }
  232. self.isMsgBeingDisplayed = NO;
  233. if (!_currentMsgBeingDisplayed.renderData.messageID) {
  234. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM400017",
  235. @"displayErrorEncountered called but "
  236. "there is no current message ID.");
  237. return;
  238. }
  239. NSString *messageID = _currentMsgBeingDisplayed.renderData.messageID;
  240. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400009",
  241. @"Display ran into error for message %@: %@", messageID, error);
  242. if (_currentMsgBeingDisplayed.isTestMessage) {
  243. [self displayMessageLoadError:error];
  244. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400012",
  245. @"A test message. No analytics tracking "
  246. "from image data loading failure");
  247. return;
  248. }
  249. // we remove the message from the client side cache so that it won't be retried until next time
  250. // it's fetched again from server.
  251. [self.messageCache removeMessageWithId:messageID];
  252. NSString *messageName = _currentMsgBeingDisplayed.renderData.name;
  253. if ([error.domain isEqualToString:NSURLErrorDomain]) {
  254. [self.analyticsEventLogger
  255. logAnalyticsEventForType:FIRIAMAnalyticsEventImageFetchError
  256. forCampaignID:messageID
  257. withCampaignName:messageName
  258. eventTimeInMs:nil
  259. completion:^(BOOL success) {
  260. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400010",
  261. @"Logging analytics event for image fetch error %@",
  262. success ? @"succeeded" : @"failed");
  263. }];
  264. } else if (error.code == FIRIAMSDKRuntimeErrorNonImageMimetypeFromImageURL) {
  265. [self.analyticsEventLogger
  266. logAnalyticsEventForType:FIRIAMAnalyticsEventImageFormatUnsupported
  267. forCampaignID:messageID
  268. withCampaignName:messageName
  269. eventTimeInMs:nil
  270. completion:^(BOOL success) {
  271. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400013",
  272. @"Logging analytics event for image format error %@",
  273. success ? @"succeeded" : @"failed");
  274. }];
  275. }
  276. }
  277. - (void)recordValidImpression:(NSString *)messageID withMessageName:(NSString *)messageName {
  278. if (!self.impressionRecorded) {
  279. [self.displayBookKeeper
  280. recordNewImpressionForMessage:messageID
  281. withStartTimestampInSeconds:[self.timeFetcher currentTimestampInSeconds]];
  282. self.impressionRecorded = YES;
  283. [self.messageCache removeMessageWithId:messageID];
  284. // Log an impression analytics event as well.
  285. [self.analyticsEventLogger
  286. logAnalyticsEventForType:FIRIAMAnalyticsEventMessageImpression
  287. forCampaignID:messageID
  288. withCampaignName:messageName
  289. eventTimeInMs:nil
  290. completion:^(BOOL success) {
  291. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400007",
  292. @"Logging analytics event for impression %@",
  293. success ? @"succeeded" : @"failed");
  294. }];
  295. }
  296. }
  297. - (void)displayMessageLoadError:(NSError *)error {
  298. NSString *errorMsg = error.userInfo[NSLocalizedDescriptionKey]
  299. ? error.userInfo[NSLocalizedDescriptionKey]
  300. : NSLocalizedString(@"Message loading failed", nil);
  301. UIAlertController *alert = [UIAlertController
  302. alertControllerWithTitle:@"Firebase InAppMessaging fail to load a test message"
  303. message:errorMsg
  304. preferredStyle:UIAlertControllerStyleAlert];
  305. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil)
  306. style:UIAlertActionStyleDefault
  307. handler:^(UIAlertAction *action) {
  308. self.alertWindow.hidden = NO;
  309. self.alertWindow = nil;
  310. }];
  311. [alert addAction:defaultAction];
  312. dispatch_async(dispatch_get_main_queue(), ^{
  313. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  314. if (@available(iOS 13.0, tvOS 13.0, *)) {
  315. UIWindowScene *foregroundedScene = nil;
  316. for (UIWindowScene *connectedScene in [UIApplication sharedApplication].connectedScenes) {
  317. if (connectedScene.activationState == UISceneActivationStateForegroundActive) {
  318. foregroundedScene = connectedScene;
  319. break;
  320. }
  321. }
  322. if (foregroundedScene == nil) {
  323. return;
  324. }
  325. self.alertWindow = [[UIWindow alloc] initWithWindowScene:foregroundedScene];
  326. }
  327. #else // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  328. self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  329. #endif
  330. UIViewController *alertViewController = [[UIViewController alloc] init];
  331. self.alertWindow.rootViewController = alertViewController;
  332. self.alertWindow.hidden = NO;
  333. [alertViewController presentViewController:alert animated:YES completion:nil];
  334. });
  335. }
  336. - (instancetype)initWithInAppMessaging:(FIRInAppMessaging *)inAppMessaging
  337. setting:(FIRIAMDisplaySetting *)setting
  338. messageCache:(FIRIAMMessageClientCache *)cache
  339. timeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher
  340. bookKeeper:(id<FIRIAMBookKeeper>)displayBookKeeper
  341. actionURLFollower:(FIRIAMActionURLFollower *)actionURLFollower
  342. activityLogger:(FIRIAMActivityLogger *)activityLogger
  343. analyticsEventLogger:(id<FIRIAMAnalyticsEventLogger>)analyticsEventLogger {
  344. if (self = [super init]) {
  345. _inAppMessaging = inAppMessaging;
  346. _timeFetcher = timeFetcher;
  347. _lastDisplayTime = displayBookKeeper.lastDisplayTime;
  348. _setting = setting;
  349. _messageCache = cache;
  350. _displayBookKeeper = displayBookKeeper;
  351. _isMsgBeingDisplayed = NO;
  352. _analyticsEventLogger = analyticsEventLogger;
  353. _actionURLFollower = actionURLFollower;
  354. _suppressMessageDisplay = NO; // always allow message display on startup
  355. }
  356. return self;
  357. }
  358. - (void)checkAndDisplayNextContextualMessageForAnalyticsEvent:(NSString *)eventName {
  359. // synchronizing on self so that we won't potentially enter the render flow from two
  360. // threads: example like showing analytics triggered message and a regular app open
  361. // triggered message
  362. @synchronized(self) {
  363. if (self.suppressMessageDisplay) {
  364. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400015",
  365. @"Message display is being suppressed. No contextual message rendering.");
  366. return;
  367. }
  368. if (!self.messageDisplayComponent) {
  369. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400026", @"%@",
  370. [[self class] logStringForNilMessageDisplayComponent]);
  371. return;
  372. }
  373. if (self.isMsgBeingDisplayed) {
  374. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400008",
  375. @"An in-app message display is in progress, do not check analytics event "
  376. "based message for now.");
  377. return;
  378. }
  379. // Pop up next analytics event based message to be displayed
  380. FIRIAMMessageDefinition *nextAnalyticsBasedMessage =
  381. [self.messageCache nextOnFirebaseAnalyticEventDisplayMsg:eventName];
  382. if (nextAnalyticsBasedMessage) {
  383. [self displayForMessage:nextAnalyticsBasedMessage
  384. triggerType:FIRInAppMessagingDisplayTriggerTypeOnAnalyticsEvent];
  385. }
  386. }
  387. }
  388. - (FIRInAppMessagingCardDisplay *)
  389. cardDisplayMessageWithMessageDefinition:(FIRIAMMessageDefinition *)definition
  390. portraitImageData:(FIRInAppMessagingImageData *)portraitImageData
  391. landscapeImageData:
  392. (nullable FIRInAppMessagingImageData *)landscapeImageData
  393. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  394. // For easier reference in this method.
  395. FIRIAMMessageRenderData *renderData = definition.renderData;
  396. NSString *title = renderData.contentData.titleText;
  397. NSString *body = renderData.contentData.bodyText;
  398. // Action button data is never nil for a card message.
  399. #pragma clang diagnostic push
  400. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  401. FIRInAppMessagingActionButton *primaryActionButton = [[FIRInAppMessagingActionButton alloc]
  402. initWithButtonText:renderData.contentData.actionButtonText
  403. buttonTextColor:renderData.renderingEffectSettings.btnTextColor
  404. backgroundColor:renderData.renderingEffectSettings.btnBGColor];
  405. #pragma clang diagnostic pop
  406. FIRInAppMessagingActionButton *secondaryActionButton = nil;
  407. if (definition.renderData.contentData.secondaryActionButtonText) {
  408. #pragma clang diagnostic push
  409. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  410. secondaryActionButton = [[FIRInAppMessagingActionButton alloc]
  411. initWithButtonText:renderData.contentData.secondaryActionButtonText
  412. buttonTextColor:renderData.renderingEffectSettings.secondaryActionBtnTextColor
  413. backgroundColor:renderData.renderingEffectSettings.btnBGColor];
  414. #pragma clang diagnostic pop
  415. }
  416. FIRInAppMessagingCardDisplay *cardMessage = [[FIRInAppMessagingCardDisplay alloc]
  417. initWithMessageID:renderData.messageID
  418. campaignName:renderData.name
  419. experimentPayload:definition.experimentPayload
  420. renderAsTestMessage:definition.isTestMessage
  421. triggerType:triggerType
  422. titleText:title
  423. bodyText:body
  424. textColor:renderData.renderingEffectSettings.textColor
  425. portraitImageData:portraitImageData
  426. landscapeImageData:landscapeImageData
  427. backgroundColor:renderData.renderingEffectSettings.displayBGColor
  428. primaryActionButton:primaryActionButton
  429. secondaryActionButton:secondaryActionButton
  430. primaryActionURL:definition.renderData.contentData.actionURL
  431. secondaryActionURL:definition.renderData.contentData.secondaryActionURL
  432. appData:definition.appData];
  433. return cardMessage;
  434. }
  435. - (FIRInAppMessagingBannerDisplay *)
  436. bannerDisplayMessageWithMessageDefinition:(FIRIAMMessageDefinition *)definition
  437. imageData:(FIRInAppMessagingImageData *)imageData
  438. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  439. NSString *title = definition.renderData.contentData.titleText;
  440. NSString *body = definition.renderData.contentData.bodyText;
  441. #pragma clang diagnostic push
  442. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  443. FIRInAppMessagingBannerDisplay *bannerMessage = [[FIRInAppMessagingBannerDisplay alloc]
  444. initWithMessageID:definition.renderData.messageID
  445. campaignName:definition.renderData.name
  446. experimentPayload:definition.experimentPayload
  447. renderAsTestMessage:definition.isTestMessage
  448. triggerType:triggerType
  449. titleText:title
  450. bodyText:body
  451. textColor:definition.renderData.renderingEffectSettings.textColor
  452. backgroundColor:definition.renderData.renderingEffectSettings.displayBGColor
  453. imageData:imageData
  454. actionURL:definition.renderData.contentData.actionURL
  455. appData:definition.appData];
  456. #pragma clang diagnostic pop
  457. return bannerMessage;
  458. }
  459. - (FIRInAppMessagingImageOnlyDisplay *)
  460. imageOnlyDisplayMessageWithMessageDefinition:(FIRIAMMessageDefinition *)definition
  461. imageData:(FIRInAppMessagingImageData *)imageData
  462. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  463. #pragma clang diagnostic push
  464. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  465. FIRInAppMessagingImageOnlyDisplay *imageOnlyMessage = [[FIRInAppMessagingImageOnlyDisplay alloc]
  466. initWithMessageID:definition.renderData.messageID
  467. campaignName:definition.renderData.name
  468. experimentPayload:definition.experimentPayload
  469. renderAsTestMessage:definition.isTestMessage
  470. triggerType:triggerType
  471. imageData:imageData
  472. actionURL:definition.renderData.contentData.actionURL
  473. appData:definition.appData];
  474. #pragma clang diagnostic pop
  475. return imageOnlyMessage;
  476. }
  477. - (FIRInAppMessagingModalDisplay *)
  478. modalDisplayMessageWithMessageDefinition:(FIRIAMMessageDefinition *)definition
  479. imageData:(FIRInAppMessagingImageData *)imageData
  480. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  481. // For easier reference in this method.
  482. FIRIAMMessageRenderData *renderData = definition.renderData;
  483. NSString *title = renderData.contentData.titleText;
  484. NSString *body = renderData.contentData.bodyText;
  485. FIRInAppMessagingActionButton *actionButton = nil;
  486. if (definition.renderData.contentData.actionButtonText) {
  487. #pragma clang diagnostic push
  488. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  489. actionButton = [[FIRInAppMessagingActionButton alloc]
  490. initWithButtonText:renderData.contentData.actionButtonText
  491. buttonTextColor:renderData.renderingEffectSettings.btnTextColor
  492. backgroundColor:renderData.renderingEffectSettings.btnBGColor];
  493. #pragma clang diagnostic pop
  494. }
  495. #pragma clang diagnostic push
  496. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  497. FIRInAppMessagingModalDisplay *modalViewMessage = [[FIRInAppMessagingModalDisplay alloc]
  498. initWithMessageID:definition.renderData.messageID
  499. campaignName:definition.renderData.name
  500. experimentPayload:definition.experimentPayload
  501. renderAsTestMessage:definition.isTestMessage
  502. triggerType:triggerType
  503. titleText:title
  504. bodyText:body
  505. textColor:renderData.renderingEffectSettings.textColor
  506. backgroundColor:renderData.renderingEffectSettings.displayBGColor
  507. imageData:imageData
  508. actionButton:actionButton
  509. actionURL:definition.renderData.contentData.actionURL
  510. appData:definition.appData];
  511. #pragma clang diagnostic pop
  512. return modalViewMessage;
  513. }
  514. - (FIRInAppMessagingDisplayMessage *)
  515. displayMessageWithMessageDefinition:(FIRIAMMessageDefinition *)definition
  516. imageData:(FIRInAppMessagingImageData *)imageData
  517. landscapeImageData:(nullable FIRInAppMessagingImageData *)landscapeImageData
  518. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  519. switch (definition.renderData.renderingEffectSettings.viewMode) {
  520. case FIRIAMRenderAsCardView:
  521. if (imageData == nil) {
  522. // Image data should never nil for a valid card message.
  523. return nil;
  524. }
  525. return [self cardDisplayMessageWithMessageDefinition:definition
  526. portraitImageData:imageData
  527. landscapeImageData:landscapeImageData
  528. triggerType:triggerType];
  529. case FIRIAMRenderAsBannerView:
  530. return [self bannerDisplayMessageWithMessageDefinition:definition
  531. imageData:imageData
  532. triggerType:triggerType];
  533. case FIRIAMRenderAsModalView:
  534. return [self modalDisplayMessageWithMessageDefinition:definition
  535. imageData:imageData
  536. triggerType:triggerType];
  537. case FIRIAMRenderAsImageOnlyView:
  538. return [self imageOnlyDisplayMessageWithMessageDefinition:definition
  539. imageData:imageData
  540. triggerType:triggerType];
  541. default:
  542. return nil;
  543. }
  544. }
  545. - (void)displayForMessage:(FIRIAMMessageDefinition *)message
  546. triggerType:(FIRInAppMessagingDisplayTriggerType)triggerType {
  547. _currentMsgBeingDisplayed = message;
  548. self.isMsgBeingDisplayed = YES;
  549. [message.renderData.contentData
  550. loadImageDataWithBlock:^(NSData *_Nullable standardImageRawData,
  551. NSData *_Nullable landscapeImageRawData, NSError *_Nullable error) {
  552. FIRInAppMessagingImageData *imageData = nil;
  553. FIRInAppMessagingImageData *landscapeImageData = nil;
  554. if (error) {
  555. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400019",
  556. @"Error in loading image data for the message.");
  557. FIRInAppMessagingDisplayMessage *erroredMessage =
  558. [self displayMessageWithMessageDefinition:message
  559. imageData:imageData
  560. landscapeImageData:landscapeImageData
  561. triggerType:triggerType];
  562. // short-circuit to display error handling
  563. [self displayErrorForMessage:erroredMessage error:error];
  564. self.isMsgBeingDisplayed = NO;
  565. return;
  566. } else {
  567. if (standardImageRawData) {
  568. #pragma clang diagnostic push
  569. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  570. imageData = [[FIRInAppMessagingImageData alloc]
  571. initWithImageURL:message.renderData.contentData.imageURL.absoluteString
  572. imageData:standardImageRawData];
  573. #pragma clang diagnostic pop
  574. }
  575. if (landscapeImageRawData) {
  576. #pragma clang diagnostic push
  577. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  578. landscapeImageData = [[FIRInAppMessagingImageData alloc]
  579. initWithImageURL:message.renderData.contentData.landscapeImageURL.absoluteString
  580. imageData:landscapeImageRawData];
  581. #pragma clang diagnostic pop
  582. }
  583. }
  584. // On slow networks, image loading may take significant time,
  585. // in which the value of `suppressMessageDisplay` could change.
  586. if (self.suppressMessageDisplay) {
  587. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400042",
  588. @"Message display suppressed by developer at message display time.");
  589. self.isMsgBeingDisplayed = NO;
  590. return;
  591. }
  592. self.impressionRecorded = NO;
  593. FIRInAppMessagingDisplayMessage *displayMessage =
  594. [self displayMessageWithMessageDefinition:message
  595. imageData:imageData
  596. landscapeImageData:landscapeImageData
  597. triggerType:triggerType];
  598. // A final `nil`-check, performed to avoid crashing the client app.
  599. if (!displayMessage) {
  600. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400043",
  601. @"Failed to construct a non-nil display message.");
  602. return;
  603. }
  604. [self.messageDisplayComponent displayMessage:displayMessage displayDelegate:self];
  605. }];
  606. }
  607. - (BOOL)enoughIntervalFromLastDisplay {
  608. NSTimeInterval intervalFromLastDisplayInSeconds =
  609. [self.timeFetcher currentTimestampInSeconds] - self.lastDisplayTime;
  610. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400005",
  611. @"Interval time from last display is %lf seconds", intervalFromLastDisplayInSeconds);
  612. return intervalFromLastDisplayInSeconds >= self.setting.displayMinIntervalInMinutes * 60.0;
  613. }
  614. - (void)checkAndDisplayNextAppLaunchMessage {
  615. // synchronizing on self so that we won't potentially enter the render flow from two
  616. // threads.
  617. @synchronized(self) {
  618. if (!self.messageDisplayComponent) {
  619. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400028", @"%@",
  620. [[self class] logStringForNilMessageDisplayComponent]);
  621. return;
  622. }
  623. if (self.suppressMessageDisplay) {
  624. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400029",
  625. @"Message display is being suppressed. No regular message rendering.");
  626. return;
  627. }
  628. if (self.isMsgBeingDisplayed) {
  629. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400030",
  630. @"An in-app message display is in progress, do not over-display on top of it.");
  631. return;
  632. }
  633. if ([self.messageCache hasTestMessage] || [self enoughIntervalFromLastDisplay]) {
  634. // We can display test messages anytime or display regular messages when
  635. // the display time interval has been reached
  636. FIRIAMMessageDefinition *nextAppLaunchMessage = [self.messageCache nextOnAppLaunchDisplayMsg];
  637. if (nextAppLaunchMessage) {
  638. [self displayForMessage:nextAppLaunchMessage
  639. triggerType:FIRInAppMessagingDisplayTriggerTypeOnAnalyticsEvent];
  640. self.lastDisplayTime = [self.timeFetcher currentTimestampInSeconds];
  641. } else {
  642. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400040",
  643. @"No appropriate in-app message detected for display.");
  644. }
  645. } else {
  646. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400041",
  647. @"Minimal display interval of %lf seconds has not been reached yet.",
  648. self.setting.displayMinIntervalInMinutes * 60.0);
  649. }
  650. }
  651. }
  652. - (void)checkAndDisplayNextAppForegroundMessage {
  653. // synchronizing on self so that we won't potentially enter the render flow from two
  654. // threads: example like showing analytics triggered message and a regular app open
  655. // triggered message concurrently
  656. @synchronized(self) {
  657. if (!self.messageDisplayComponent) {
  658. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400027", @"%@",
  659. [[self class] logStringForNilMessageDisplayComponent]);
  660. return;
  661. }
  662. if (self.suppressMessageDisplay) {
  663. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400016",
  664. @"Message display is being suppressed. No regular message rendering.");
  665. return;
  666. }
  667. if (self.isMsgBeingDisplayed) {
  668. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400002",
  669. @"An in-app message display is in progress, do not over-display on top of it.");
  670. return;
  671. }
  672. if ([self.messageCache hasTestMessage] || [self enoughIntervalFromLastDisplay]) {
  673. // We can display test messages anytime or display regular messages when
  674. // the display time interval has been reached
  675. FIRIAMMessageDefinition *nextForegroundMessage = [self.messageCache nextOnAppOpenDisplayMsg];
  676. if (nextForegroundMessage) {
  677. [self displayForMessage:nextForegroundMessage
  678. triggerType:FIRInAppMessagingDisplayTriggerTypeOnAppForeground];
  679. self.lastDisplayTime = [self.timeFetcher currentTimestampInSeconds];
  680. } else {
  681. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400001",
  682. @"No appropriate in-app message detected for display.");
  683. }
  684. } else {
  685. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM400003",
  686. @"Minimal display interval of %lf seconds has not been reached yet.",
  687. self.setting.displayMinIntervalInMinutes * 60.0);
  688. }
  689. }
  690. }
  691. @end
  692. #endif // TARGET_OS_IOS || TARGET_OS_TV