FIRIAMDisplayExecutor.m 35 KB

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