FIRIAMBannerViewController.m 12 KB

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