FIDModalViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * Copyright 2018 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 <UIKit/UIKit.h>
  17. #import <FirebaseInAppMessaging/FIRInAppMessagingRendering.h>
  18. #import "FIDModalViewController.h"
  19. #import "FIRCore+InAppMessagingDisplay.h"
  20. @interface FIDModalViewController ()
  21. @property(nonatomic, readwrite) FIRInAppMessagingModalDisplay *modalDisplayMessage;
  22. @property(weak, nonatomic) IBOutlet UIImageView *imageView;
  23. @property(weak, nonatomic) IBOutlet UILabel *titleLabel;
  24. @property(weak, nonatomic) IBOutlet UIButton *actionButton;
  25. @property(weak, nonatomic) IBOutlet UIView *messageCardView;
  26. @property(weak, nonatomic) IBOutlet UITextView *bodyTextView;
  27. @property(weak, nonatomic) IBOutlet UIButton *closeButton;
  28. // this is only needed for removing the layout errors in interface builder. At runtime
  29. // we determine the height via its content size. So disable this at runtime.
  30. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *fixedMessageCardHeightConstraint;
  31. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *messageCardHeightMaxInTabletCase;
  32. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *maxActionButtonHeight;
  33. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *bodyTextViewHeightConstraint;
  34. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopToBodyBottomConstraint;
  35. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageActualHeightConstraint;
  36. // constraints manipulated further in portrait mode
  37. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *titleLabelHeightConstraint;
  38. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *buttonBottomToContainerBottomInPortraitMode;
  39. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageTopToTitleBottomInPortraitMode;
  40. // constraints manipulated further in landscape mode
  41. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageWidthInLandscapeMode;
  42. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *titleTopToCardViewTop;
  43. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *cardLeadingMarginInLandscapeMode;
  44. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *maxCardHeightInLandscapeMode;
  45. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageTopToCardTopInLandscapeMode;
  46. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *bodyTopToTitleBottomInLandScapeMode;
  47. @end
  48. static CGFloat VerticalSpacingBetweenTitleAndBody = 24;
  49. static CGFloat VerticalSpacingBetweenBodyAndActionButton = 24;
  50. // the padding between the content and view card's top and bottom edges
  51. static CGFloat TopBottomPaddingAroundContent = 24;
  52. // the minimal padding size between msg card and app window's top and bottom
  53. static CGFloat TopBottomPaddingAroundMsgCard = 30;
  54. // the horizontal spacing between image column and text/button column in landscape mode
  55. static CGFloat LandScapePaddingBetweenImageAndTextColumn = 24;
  56. @implementation FIDModalViewController
  57. + (FIDModalViewController *)
  58. instantiateViewControllerWithResourceBundle:(NSBundle *)resourceBundle
  59. displayMessage:(FIRInAppMessagingModalDisplay *)modalMessage
  60. displayDelegate:
  61. (id<FIRInAppMessagingDisplayDelegate>)displayDelegate
  62. timeFetcher:(id<FIDTimeFetcher>)timeFetcher {
  63. UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"FIRInAppMessageDisplayStoryboard"
  64. bundle:resourceBundle];
  65. if (storyboard == nil) {
  66. FIRLogError(kFIRLoggerInAppMessagingDisplay, @"I-FID300001",
  67. @"Storyboard '"
  68. "FIRInAppMessageDisplayStoryboard' not found in bundle %@",
  69. resourceBundle);
  70. return nil;
  71. }
  72. FIDModalViewController *modalVC = (FIDModalViewController *)[storyboard
  73. instantiateViewControllerWithIdentifier:@"modal-view-vc"];
  74. modalVC.displayDelegate = displayDelegate;
  75. modalVC.modalDisplayMessage = modalMessage;
  76. modalVC.timeFetcher = timeFetcher;
  77. return modalVC;
  78. }
  79. - (IBAction)closeButtonClicked:(id)sender {
  80. [self dismissView:FIRInAppMessagingDismissTypeUserTapClose];
  81. }
  82. - (IBAction)actionButtonTapped:(id)sender {
  83. [self followActionURL];
  84. }
  85. - (void)viewDidLoad {
  86. [super viewDidLoad];
  87. // make the background half transparent
  88. [self.view setBackgroundColor:[UIColor.grayColor colorWithAlphaComponent:0.5]];
  89. // populating values for display elements
  90. self.titleLabel.text = self.modalDisplayMessage.title;
  91. self.bodyTextView.text = self.modalDisplayMessage.bodyText;
  92. if (self.modalDisplayMessage.imageData) {
  93. [self.imageView
  94. setImage:[UIImage imageWithData:self.modalDisplayMessage.imageData.imageRawData]];
  95. self.imageView.contentMode = UIViewContentModeScaleAspectFit;
  96. }
  97. self.messageCardView.backgroundColor = self.modalDisplayMessage.displayBackgroundColor;
  98. self.messageCardView.layer.cornerRadius = 4;
  99. self.titleLabel.textColor = self.modalDisplayMessage.textColor;
  100. self.bodyTextView.textColor = self.modalDisplayMessage.textColor;
  101. self.bodyTextView.selectable = NO;
  102. if (self.modalDisplayMessage.actionButton.buttonText.length != 0) {
  103. [self.actionButton setTitle:self.modalDisplayMessage.actionButton.buttonText
  104. forState:UIControlStateNormal];
  105. self.actionButton.backgroundColor = self.modalDisplayMessage.actionButton.buttonBackgroundColor;
  106. [self.actionButton setTitleColor:self.modalDisplayMessage.actionButton.buttonTextColor
  107. forState:UIControlStateNormal];
  108. self.actionButton.layer.cornerRadius = 4;
  109. if (self.modalDisplayMessage.bodyText.length == 0) {
  110. self.buttonTopToBodyBottomConstraint.constant = 0;
  111. }
  112. } else {
  113. // either action button text is empty or nil
  114. // hide the action button and reclaim the space below the buttom
  115. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300002",
  116. @"Modal view to be rendered without action button");
  117. self.maxActionButtonHeight.constant = 0;
  118. self.actionButton.clipsToBounds = YES;
  119. self.buttonTopToBodyBottomConstraint.constant = 0;
  120. }
  121. [self.view addConstraint:self.imageActualHeightConstraint];
  122. self.imageActualHeightConstraint.active = YES;
  123. self.fixedMessageCardHeightConstraint.active = NO;
  124. }
  125. // for text display UIview, which could be a UILabel or UITextView, decide the fit height under a
  126. // given display width
  127. - (CGFloat)determineTextAreaViewFitHeightForView:(UIView *)textView
  128. withWidth:(CGFloat)displayWidth {
  129. CGSize displaySize = CGSizeMake(displayWidth, FLT_MAX);
  130. return [textView sizeThatFits:displaySize].height;
  131. }
  132. // In both landscape or portrait mode, the title, body & button are aligned vertically and they form
  133. // together have an impact on the height for that column. Many times, we need to calculate a
  134. // suitable heights for them to help decide the layout. The height calculation is influced by quite
  135. // a few factors: the text lenght of title and body, the presence/absense of body & button and
  136. // available card/window sizes. So these are wrapped within
  137. // estimateTextButtomColumnHeightWithDisplayWidth which produce a TitleBodyButtonHeightInfo struct
  138. // to give the estimates of the heights of different elements.
  139. struct TitleBodyButtonHeightInfo {
  140. CGFloat titleHeight;
  141. CGFloat bodyHeight;
  142. // this is the total height of title plus body plus the button. Notice that button or body are
  143. // optional and the result totaColumnlHeight factor in these cases correctly
  144. CGFloat totaColumnlHeight;
  145. };
  146. - (struct TitleBodyButtonHeightInfo)estimateTextBtnColumnHeightWithDisplayWidth:
  147. (CGFloat)displayWidth
  148. withMaxColumnHeight:(CGFloat)maxHeight {
  149. struct TitleBodyButtonHeightInfo resultHeightInfo;
  150. CGFloat titleFitHeight = [self determineTextAreaViewFitHeightForView:self.titleLabel
  151. withWidth:displayWidth];
  152. CGFloat bodyFitHeight = self.modalDisplayMessage.bodyText.length == 0
  153. ? 0
  154. : [self determineTextAreaViewFitHeightForView:self.bodyTextView
  155. withWidth:displayWidth];
  156. CGFloat bodyFitHeightWithPadding = self.modalDisplayMessage.bodyText.length == 0
  157. ? 0
  158. : bodyFitHeight + VerticalSpacingBetweenTitleAndBody;
  159. CGFloat buttonHeight =
  160. self.modalDisplayMessage.actionButton == nil
  161. ? 0
  162. : self.actionButton.frame.size.height + VerticalSpacingBetweenBodyAndActionButton;
  163. // we keep the spacing even if body or button is absent.
  164. CGFloat fitColumnHeight = titleFitHeight + bodyFitHeightWithPadding + buttonHeight;
  165. if (fitColumnHeight < maxHeight) {
  166. // every element get space that can fit the content
  167. resultHeightInfo.bodyHeight = bodyFitHeight;
  168. resultHeightInfo.titleHeight = titleFitHeight;
  169. resultHeightInfo.totaColumnlHeight = fitColumnHeight;
  170. } else {
  171. // need to restrict heights of certain elements
  172. resultHeightInfo.totaColumnlHeight = maxHeight;
  173. if (self.modalDisplayMessage.bodyText.length == 0) {
  174. // no message body, title will try to expand to take all the available height
  175. resultHeightInfo.bodyHeight = 0;
  176. if (self.modalDisplayMessage.actionButton == nil) {
  177. resultHeightInfo.titleHeight = maxHeight;
  178. } else {
  179. // button height, if not 0, already accommodates the space above it
  180. resultHeightInfo.titleHeight = maxHeight - buttonHeight;
  181. }
  182. } else {
  183. // first give title up to 40% of available height
  184. resultHeightInfo.titleHeight = fmin(titleFitHeight, maxHeight * 2 / 5);
  185. CGFloat availableBodyHeight = 0;
  186. if (self.modalDisplayMessage.actionButton == nil) {
  187. availableBodyHeight =
  188. maxHeight - resultHeightInfo.titleHeight - VerticalSpacingBetweenTitleAndBody;
  189. } else {
  190. // body takes the rest minus button space
  191. availableBodyHeight = maxHeight - resultHeightInfo.titleHeight - buttonHeight -
  192. VerticalSpacingBetweenTitleAndBody;
  193. }
  194. if (availableBodyHeight > bodyFitHeight) {
  195. resultHeightInfo.bodyHeight = bodyFitHeight;
  196. // give some back to title height since body does not use up all the allocation
  197. resultHeightInfo.titleHeight += (availableBodyHeight - bodyFitHeight);
  198. } else {
  199. resultHeightInfo.bodyHeight = availableBodyHeight;
  200. }
  201. }
  202. }
  203. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300003",
  204. @"In heights calculation (max-height = %lf, width = %lf), title heights is %lf, "
  205. "body height is %lf, button height is %lf, total column heights are %lf",
  206. maxHeight, displayWidth, resultHeightInfo.titleHeight, resultHeightInfo.bodyHeight,
  207. buttonHeight, resultHeightInfo.totaColumnlHeight);
  208. return resultHeightInfo;
  209. }
  210. // the following two layoutFineTunexx methods make additional adjustments for the view layout
  211. // in portrait and landscape mode respectively. They are supposed to be triggered from
  212. // viewDidLayoutSubviews since certain dimension sizes are only available there
  213. - (void)layoutFineTuneInPortraitMode {
  214. // for tablet case, since we use a fixed card height, the reference would be just the card height
  215. // for non-tablet case, we want to use a dynamic height , so the reference would be the window
  216. // height
  217. CGFloat heightCalcReference =
  218. self.messageCardHeightMaxInTabletCase.active
  219. ? self.messageCardView.frame.size.height - TopBottomPaddingAroundContent * 2
  220. : self.view.window.frame.size.height - TopBottomPaddingAroundContent * 2 -
  221. TopBottomPaddingAroundMsgCard * 2;
  222. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300004",
  223. @"The height calc reference is %lf "
  224. "with frame height as %lf",
  225. heightCalcReference, self.view.window.frame.size.height);
  226. // this makes sure titleLable gets correct width to be ready for later's height estimate for the
  227. // text & button column
  228. [self.messageCardView layoutIfNeeded];
  229. // we reserve approximately 1/3 vertical space for image
  230. CGFloat textBtnTotalAvailableHeight =
  231. self.modalDisplayMessage.imageData ? heightCalcReference * 2 / 3 : heightCalcReference;
  232. struct TitleBodyButtonHeightInfo heights =
  233. [self estimateTextBtnColumnHeightWithDisplayWidth:self.titleLabel.frame.size.width
  234. withMaxColumnHeight:textBtnTotalAvailableHeight];
  235. self.titleLabelHeightConstraint.constant = heights.titleHeight;
  236. self.bodyTextViewHeightConstraint.constant = heights.bodyHeight;
  237. if (self.modalDisplayMessage.imageData) {
  238. UIImage *image = [UIImage imageWithData:self.modalDisplayMessage.imageData.imageRawData];
  239. CGSize imageAvailableSpace = CGSizeMake(self.titleLabel.frame.size.width,
  240. heightCalcReference - heights.totaColumnlHeight -
  241. self.imageTopToTitleBottomInPortraitMode.constant);
  242. CGSize imageDisplaySize = [self fitImageInRegionSize:imageAvailableSpace
  243. withImageSize:image.size];
  244. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300005",
  245. @"Given actual image size %@ and available image display size %@, the actual"
  246. "image display size is %@",
  247. NSStringFromCGSize(image.size), NSStringFromCGSize(imageAvailableSpace),
  248. NSStringFromCGSize(imageDisplaySize));
  249. // for portrait mode, no need to change image width since no content is shown side to
  250. // the image
  251. self.imageActualHeightConstraint.constant = imageDisplaySize.height;
  252. } else {
  253. // no image case
  254. self.imageActualHeightConstraint.constant = 0;
  255. self.imageTopToTitleBottomInPortraitMode.constant = 0;
  256. }
  257. }
  258. - (CGSize)fitImageInRegionSize:(CGSize)regionSize withImageSize:(CGSize)imageSize {
  259. if (imageSize.height <= regionSize.height && imageSize.width <= regionSize.width) {
  260. return imageSize; // image can be fully rendered at its original dimension
  261. } else {
  262. CGFloat regionRatio = regionSize.width / regionSize.height;
  263. CGFloat imageRaio = imageSize.width / imageSize.height;
  264. if (regionRatio < imageRaio) {
  265. // bound on the width dimension
  266. return CGSizeMake(regionSize.width, regionSize.width / imageRaio);
  267. } else {
  268. return CGSizeMake(regionSize.height * imageRaio, regionSize.height);
  269. }
  270. }
  271. }
  272. // for devices of 4 inches or below (iphone se, iphone 5/5s and iphone 4s), reduce
  273. // the padding sizes between elements in the text/button column for landscape mode
  274. - (void)applySmallerSpacingForInLandscapeMode {
  275. if (self.modalDisplayMessage.bodyText.length != 0) {
  276. VerticalSpacingBetweenTitleAndBody = self.bodyTopToTitleBottomInLandScapeMode.constant = 12;
  277. }
  278. if (self.modalDisplayMessage.actionButton != nil &&
  279. self.modalDisplayMessage.bodyText.length != 0) {
  280. VerticalSpacingBetweenBodyAndActionButton = self.buttonTopToBodyBottomConstraint.constant = 12;
  281. }
  282. }
  283. - (void)layoutFineTuneInLandscapeMode {
  284. // smaller spacing threshold is applied for screens equal or larger than 4.7 inches
  285. if (self.view.window.frame.size.height <= 321) {
  286. [self applySmallerSpacingForInLandscapeMode];
  287. }
  288. if (self.modalDisplayMessage.imageData) {
  289. UIImage *image = [UIImage imageWithData:self.modalDisplayMessage.imageData.imageRawData];
  290. CGFloat maxImageHeight = self.view.window.frame.size.height -
  291. TopBottomPaddingAroundContent * 2 - TopBottomPaddingAroundMsgCard * 2;
  292. CGFloat maxImageWidth = self.messageCardView.frame.size.width * 2 / 5;
  293. CGSize imageDisplaySize = [self fitImageInRegionSize:CGSizeMake(maxImageWidth, maxImageHeight)
  294. withImageSize:image.size];
  295. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300008",
  296. @"In landscape mode, image fit size is %@", NSStringFromCGSize(imageDisplaySize));
  297. // resize image per imageSize
  298. self.imageWidthInLandscapeMode.constant = imageDisplaySize.width;
  299. self.imageActualHeightConstraint.constant = imageDisplaySize.height;
  300. // now we can estimate the new card width given the desired image size
  301. // this assumes we use half of the window width for diplaying the text/button column
  302. CGFloat cardFitWidth = imageDisplaySize.width + self.view.window.frame.size.width / 2 +
  303. LandScapePaddingBetweenImageAndTextColumn;
  304. self.cardLeadingMarginInLandscapeMode.constant =
  305. fmax(15, (self.view.window.frame.size.width - cardFitWidth) / 2);
  306. } else {
  307. self.imageWidthInLandscapeMode.constant = 0;
  308. self.imageActualHeightConstraint.constant = 0;
  309. // card would be of 3/5 width of the screen in landscape
  310. self.cardLeadingMarginInLandscapeMode.constant = self.view.window.frame.size.width / 5;
  311. }
  312. // this makes sure titleLable gets correct width to be ready for later's height estimate for the
  313. // text & button column
  314. [self.messageCardView layoutIfNeeded];
  315. struct TitleBodyButtonHeightInfo heights =
  316. [self estimateTextBtnColumnHeightWithDisplayWidth:self.titleLabel.frame.size.width
  317. withMaxColumnHeight:self.view.frame.size.height -
  318. TopBottomPaddingAroundContent * 2 -
  319. TopBottomPaddingAroundMsgCard * 2];
  320. self.titleLabelHeightConstraint.constant = heights.titleHeight;
  321. self.bodyTextViewHeightConstraint.constant = heights.bodyHeight;
  322. // Adjust the height of the card
  323. // are we bound by the text/button column height or image height ?
  324. CGFloat cardHeight = fmax(self.imageActualHeightConstraint.constant, heights.totaColumnlHeight) +
  325. TopBottomPaddingAroundContent * 2;
  326. self.maxCardHeightInLandscapeMode.constant = cardHeight;
  327. // with the new card height, align the image and the text/btn column to center vertically
  328. self.imageTopToCardTopInLandscapeMode.constant =
  329. (cardHeight - self.imageActualHeightConstraint.constant) / 2;
  330. self.titleTopToCardViewTop.constant = (cardHeight - heights.totaColumnlHeight) / 2;
  331. }
  332. - (void)viewDidLayoutSubviews {
  333. [super viewDidLayoutSubviews];
  334. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular ||
  335. self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact) {
  336. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300010",
  337. @"Modal view rendered in landscape mode");
  338. [self layoutFineTuneInLandscapeMode];
  339. } else {
  340. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300009",
  341. @"Modal view rendered in portrait mode");
  342. [self layoutFineTuneInPortraitMode];
  343. }
  344. // always scroll to the top in case the body area is scrollable
  345. [self.bodyTextView setContentOffset:CGPointZero];
  346. }
  347. - (void)viewWillAppear:(BOOL)animated {
  348. [super viewWillAppear:animated];
  349. // close any potential keyboard, which would conflict with the modal in-app messagine view
  350. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
  351. to:nil
  352. from:nil
  353. forEvent:nil];
  354. if (self.modalDisplayMessage.renderAsTestMessage) {
  355. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300011",
  356. @"Flushing the close button since this is a test message.");
  357. [self flashCloseButton:self.closeButton];
  358. }
  359. }
  360. - (void)flashCloseButton:(UIButton *)closeButton {
  361. closeButton.alpha = 1.0f;
  362. [UIView animateWithDuration:2.0
  363. delay:0.0
  364. options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionRepeat |
  365. UIViewAnimationOptionAutoreverse |
  366. UIViewAnimationOptionAllowUserInteraction
  367. animations:^{
  368. closeButton.alpha = 0.1f;
  369. }
  370. completion:^(BOOL finished){
  371. // Do nothing
  372. }];
  373. }
  374. @end