FIDBannerViewController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 <FirebaseInAppMessaging/FIRInAppMessagingRendering.h>
  17. #import "FIDBannerViewController.h"
  18. #import "FIRCore+InAppMessagingDisplay.h"
  19. @interface FIDBannerViewController ()
  20. @property(nonatomic, readwrite) FIRInAppMessagingBannerDisplay *bannerDisplayMessage;
  21. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageViewWidthConstraint;
  22. @property(weak, nonatomic) IBOutlet NSLayoutConstraint *imageViewHeightConstraint;
  23. @property(weak, nonatomic)
  24. IBOutlet NSLayoutConstraint *imageBottomAlignWithBodyLabelBottomConstraint;
  25. @property(weak, nonatomic) IBOutlet UIImageView *imageView;
  26. @property(weak, nonatomic) IBOutlet UILabel *titleLabel;
  27. @property(weak, nonatomic) IBOutlet UILabel *bodyLabel;
  28. // Banner view will be rendered and dismissed with animation. Within viewDidLayoutSubviews function,
  29. // we would position the view so that it's out of UIWindow range on the top so that later on it can
  30. // slide in with animation. However, viewDidLayoutSubviews is also triggred in other scenarios
  31. // like split view on iPad or device orientation changes where we don't want to hide the banner for
  32. // animations. So to have different logic, we use this property to tell the two different
  33. // cases apart and apply different positioning logic accordingly in viewDidLayoutSubviews.
  34. @property(nonatomic) BOOL hidingForAnimation;
  35. @property(nonatomic, nullable) NSTimer *autoDismissTimer;
  36. @end
  37. // The image display area dimension in points
  38. static const CGFloat kBannerViewImageWidth = 60;
  39. static const CGFloat kBannerViewImageHeight = 60;
  40. static const NSTimeInterval kBannerViewAnimationDuration = 0.3; // in seconds
  41. // Banner view will auto dismiss after this amount of time of showing if user does not take
  42. // any other actions. It's in seconds.
  43. static const NSTimeInterval kBannerAutoDimissTime = 12;
  44. // If the window width is larger than this threshold, we cap banner view width
  45. // by it: showing a non full-width banner when it happens.
  46. static const CGFloat kBannerViewMaxWidth = 736;
  47. static const CGFloat kSwipeUpThreshold = -10.0f;
  48. @implementation FIDBannerViewController
  49. + (FIDBannerViewController *)
  50. instantiateViewControllerWithResourceBundle:(NSBundle *)resourceBundle
  51. displayMessage:(FIRInAppMessagingBannerDisplay *)bannerMessage
  52. displayDelegate:
  53. (id<FIRInAppMessagingDisplayDelegate>)displayDelegate
  54. timeFetcher:(id<FIDTimeFetcher>)timeFetcher {
  55. UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"FIRInAppMessageDisplayStoryboard"
  56. bundle:resourceBundle];
  57. if (storyboard == nil) {
  58. FIRLogError(kFIRLoggerInAppMessagingDisplay, @"I-FID300002",
  59. @"Storyboard '"
  60. "FIRInAppMessageDisplayStoryboard' not found in bundle %@",
  61. resourceBundle);
  62. return nil;
  63. }
  64. FIDBannerViewController *bannerVC = (FIDBannerViewController *)[storyboard
  65. instantiateViewControllerWithIdentifier:@"banner-view-vc"];
  66. bannerVC.displayDelegate = displayDelegate;
  67. bannerVC.bannerDisplayMessage = bannerMessage;
  68. bannerVC.timeFetcher = timeFetcher;
  69. return bannerVC;
  70. }
  71. - (void)setupRecognizers {
  72. UIPanGestureRecognizer *panSwipeRecognizer =
  73. [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanSwipe:)];
  74. [self.view addGestureRecognizer:panSwipeRecognizer];
  75. UITapGestureRecognizer *tapGestureRecognizer =
  76. [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(messageTapped:)];
  77. tapGestureRecognizer.delaysTouchesBegan = YES;
  78. tapGestureRecognizer.numberOfTapsRequired = 1;
  79. [self.view addGestureRecognizer:tapGestureRecognizer];
  80. }
  81. - (void)handlePanSwipe:(UIPanGestureRecognizer *)recognizer {
  82. // Detect the swipe gesture
  83. if (recognizer.state == UIGestureRecognizerStateEnded) {
  84. CGPoint vel = [recognizer velocityInView:recognizer.view];
  85. if (vel.y < kSwipeUpThreshold) {
  86. [self closeViewFromManualDismiss];
  87. }
  88. }
  89. }
  90. - (void)viewDidLoad {
  91. [super viewDidLoad];
  92. // Do any additional setup after loading the view from its nib.
  93. [self setupRecognizers];
  94. self.titleLabel.text = self.bannerDisplayMessage.title;
  95. self.bodyLabel.text = self.bannerDisplayMessage.bodyText;
  96. if (self.bannerDisplayMessage.imageData) {
  97. self.imageView.contentMode = UIViewContentModeScaleAspectFit;
  98. UIImage *image = [UIImage imageWithData:self.bannerDisplayMessage.imageData.imageRawData];
  99. if (fabs(image.size.width / image.size.height - 1) > 0.02) {
  100. // width and height differ by at least 2%, need to adjust image view
  101. // size to respect the ratio
  102. // reduce height or width of the image view to retain the ratio of the image
  103. if (image.size.width > image.size.height) {
  104. CGFloat newImageHeight = kBannerViewImageWidth * image.size.height / image.size.width;
  105. self.imageViewHeightConstraint.constant = newImageHeight;
  106. } else {
  107. CGFloat newImageWidth = kBannerViewImageHeight * image.size.width / image.size.height;
  108. self.imageViewWidthConstraint.constant = newImageWidth;
  109. }
  110. }
  111. self.imageView.image = image;
  112. } else {
  113. // Hide image and remove the bottom constraint between body label and image view.
  114. self.imageViewWidthConstraint.constant = 0;
  115. self.imageBottomAlignWithBodyLabelBottomConstraint.active = NO;
  116. }
  117. // Set some rendering effects based on settings.
  118. self.view.backgroundColor = self.bannerDisplayMessage.displayBackgroundColor;
  119. self.titleLabel.textColor = self.bannerDisplayMessage.textColor;
  120. self.bodyLabel.textColor = self.bannerDisplayMessage.textColor;
  121. self.view.layer.masksToBounds = NO;
  122. self.view.layer.shadowOffset = CGSizeMake(2, 1);
  123. self.view.layer.shadowRadius = 2;
  124. self.view.layer.shadowOpacity = 0.4;
  125. // When created, we are hiding it for later animation
  126. self.hidingForAnimation = YES;
  127. [self setupAutoDismissTimer];
  128. }
  129. - (void)dismissViewWithAnimation:(void (^)(void))completion {
  130. CGRect rectInNormalState = self.view.frame;
  131. CGAffineTransform hidingTransform =
  132. CGAffineTransformMakeTranslation(0, -rectInNormalState.size.height);
  133. [UIView animateWithDuration:kBannerViewAnimationDuration
  134. delay:0
  135. options:UIViewAnimationOptionCurveEaseInOut
  136. animations:^{
  137. self.view.transform = hidingTransform;
  138. }
  139. completion:^(BOOL finished) {
  140. completion();
  141. }];
  142. }
  143. - (void)closeViewFromAutoDismiss {
  144. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300001", @"Auto dismiss the banner view");
  145. [self dismissViewWithAnimation:^(void) {
  146. [self dismissView:FIRInAppMessagingDismissTypeAuto];
  147. }];
  148. }
  149. - (void)closeViewFromManualDismiss {
  150. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300003", @"Manually dismiss the banner view");
  151. [self.autoDismissTimer invalidate];
  152. [self dismissViewWithAnimation:^(void) {
  153. [self dismissView:FIRInAppMessagingDismissTypeUserSwipe];
  154. }];
  155. }
  156. - (void)messageTapped:(UITapGestureRecognizer *)recognizer {
  157. [self.autoDismissTimer invalidate];
  158. [self dismissViewWithAnimation:^(void) {
  159. [self followActionURL];
  160. }];
  161. }
  162. - (void)adjustBodyLabelViewHeight {
  163. // These lines make sure that we only change the height of the label view
  164. // to fit the content. Doing [self.bodyLabel sizeToFit] only could potentially
  165. // change the width as well.
  166. CGRect theFrame = self.bodyLabel.frame;
  167. [self.bodyLabel sizeToFit];
  168. theFrame.size.height = self.bodyLabel.frame.size.height;
  169. self.bodyLabel.frame = theFrame;
  170. }
  171. - (void)viewDidLayoutSubviews {
  172. [super viewDidLayoutSubviews];
  173. CGFloat bannerViewHeight = 0;
  174. [self adjustBodyLabelViewHeight];
  175. if (self.bannerDisplayMessage.imageData) {
  176. CGFloat imageBottom = CGRectGetMaxY(self.imageView.frame);
  177. CGFloat bodyBottom = CGRectGetMaxY(self.bodyLabel.frame);
  178. bannerViewHeight = MAX(imageBottom, bodyBottom);
  179. } else {
  180. bannerViewHeight = CGRectGetMaxY(self.bodyLabel.frame);
  181. }
  182. bannerViewHeight += 5; // Add some padding margin on the bottom of the view
  183. CGFloat appWindowWidth = [self.view.window bounds].size.width;
  184. CGFloat bannerViewWidth = appWindowWidth;
  185. if (bannerViewWidth > kBannerViewMaxWidth) {
  186. bannerViewWidth = kBannerViewMaxWidth;
  187. self.view.layer.cornerRadius = 4;
  188. }
  189. CGRect viewRect =
  190. CGRectMake((appWindowWidth - bannerViewWidth) / 2, 0, bannerViewWidth, bannerViewHeight);
  191. self.view.frame = viewRect;
  192. if (self.hidingForAnimation) {
  193. // Move the banner to be just above the top of the window to hide it.
  194. self.view.center = CGPointMake(appWindowWidth / 2, -viewRect.size.height / 2);
  195. }
  196. }
  197. - (void)viewDidAppear:(BOOL)animated {
  198. [super viewDidAppear:animated];
  199. CGRect rectInNormalState = self.view.frame;
  200. CGPoint normalCenterPoint =
  201. CGPointMake(rectInNormalState.origin.x + rectInNormalState.size.width / 2,
  202. rectInNormalState.size.height / 2);
  203. self.hidingForAnimation = NO;
  204. [UIView animateWithDuration:kBannerViewAnimationDuration
  205. delay:0
  206. options:UIViewAnimationOptionCurveEaseInOut
  207. animations:^{
  208. self.view.center = normalCenterPoint;
  209. }
  210. completion:nil];
  211. }
  212. - (void)setupAutoDismissTimer {
  213. NSTimeInterval remaining = kBannerAutoDimissTime - super.aggregateImpressionTimeInSeconds;
  214. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300004",
  215. @"Remaining banner auto dismiss time is %lf", remaining);
  216. // Set up the auto dismiss behavior.
  217. __weak id weakSelf = self;
  218. self.autoDismissTimer =
  219. [NSTimer scheduledTimerWithTimeInterval:remaining
  220. target:weakSelf
  221. selector:@selector(closeViewFromAutoDismiss)
  222. userInfo:nil
  223. repeats:NO];
  224. }
  225. // Handlers for app become active inactive so that we can better adjust our auto dismiss feature
  226. - (void)appDidBecomeInactive:(UIApplication *)application {
  227. [super appDidBecomeInactive:application];
  228. [self.autoDismissTimer invalidate];
  229. }
  230. - (void)appDidBecomeActive:(UIApplication *)application {
  231. [super appDidBecomeActive:application];
  232. [self setupAutoDismissTimer];
  233. }
  234. - (void)dealloc {
  235. FIRLogDebug(kFIRLoggerInAppMessagingDisplay, @"I-FID300005",
  236. @"-[FIRIAMBannerViewController dealloc] triggered for %p", self);
  237. [self.autoDismissTimer invalidate];
  238. }
  239. @end