FBAlertsMonitor.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. #import "FBAlertsMonitor.h"
  10. #import "FBAlert.h"
  11. #import "FBLogger.h"
  12. #import "XCUIApplication+FBAlert.h"
  13. #import "XCUIApplication+FBHelpers.h"
  14. static const NSTimeInterval FB_MONTORING_INTERVAL = 2.0;
  15. @interface FBAlertsMonitor()
  16. @property (atomic) BOOL isMonitoring;
  17. @end
  18. @implementation FBAlertsMonitor
  19. - (instancetype)init
  20. {
  21. if ((self = [super init])) {
  22. _isMonitoring = NO;
  23. _delegate = nil;
  24. }
  25. return self;
  26. }
  27. - (void)scheduleNextTick
  28. {
  29. if (!self.isMonitoring) {
  30. return;
  31. }
  32. dispatch_time_t delta = (int64_t)(FB_MONTORING_INTERVAL * NSEC_PER_SEC);
  33. if (nil == self.delegate) {
  34. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta), dispatch_get_main_queue(), ^{
  35. [self scheduleNextTick];
  36. });
  37. return;
  38. }
  39. dispatch_async(dispatch_get_main_queue(), ^{
  40. NSArray<XCUIApplication *> *activeApps = XCUIApplication.fb_activeApplications;
  41. for (XCUIApplication *activeApp in activeApps) {
  42. XCUIElement *alertElement = nil;
  43. @try {
  44. alertElement = activeApp.fb_alertElement;
  45. if (nil != alertElement) {
  46. [self.delegate didDetectAlert:[FBAlert alertWithElement:alertElement]];
  47. }
  48. } @catch (NSException *e) {
  49. [FBLogger logFmt:@"Got an unexpected exception while monitoring alerts: %@\n%@", e.reason, e.callStackSymbols];
  50. }
  51. if (nil != alertElement) {
  52. break;
  53. }
  54. }
  55. if (self.isMonitoring) {
  56. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta), dispatch_get_main_queue(), ^{
  57. [self scheduleNextTick];
  58. });
  59. }
  60. });
  61. }
  62. - (void)enable
  63. {
  64. if (self.isMonitoring) {
  65. return;
  66. }
  67. self.isMonitoring = YES;
  68. [self scheduleNextTick];
  69. }
  70. - (void)disable
  71. {
  72. if (!self.isMonitoring) {
  73. return;
  74. }
  75. self.isMonitoring = NO;
  76. }
  77. @end