LifecycleNotifications.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // Copyright 2022 Google LLC
  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. import XCTest
  16. import Dispatch
  17. #if os(iOS) || os(tvOS)
  18. import UIKit
  19. #elseif os(macOS)
  20. import Cocoa
  21. import AppKit
  22. #elseif os(watchOS)
  23. import WatchKit
  24. #endif
  25. extension XCTestCase {
  26. func postBackgroundedNotification() {
  27. // On Catalyst, the notifications can only be called on a the main thread
  28. if Thread.isMainThread {
  29. postBackgroundedNotificationInternal()
  30. } else {
  31. DispatchQueue.main.sync {
  32. self.postBackgroundedNotificationInternal()
  33. }
  34. }
  35. }
  36. private func postBackgroundedNotificationInternal() {
  37. let notificationCenter = NotificationCenter.default
  38. #if os(iOS) || os(tvOS)
  39. notificationCenter.post(name: UIApplication.didEnterBackgroundNotification, object: nil)
  40. #elseif os(macOS)
  41. notificationCenter.post(name: NSApplication.didResignActiveNotification, object: nil)
  42. #elseif os(watchOS)
  43. if #available(watchOSApplicationExtension 7.0, *) {
  44. notificationCenter.post(
  45. name: WKExtension.applicationDidEnterBackgroundNotification,
  46. object: nil
  47. )
  48. }
  49. #endif
  50. }
  51. func postForegroundedNotification() {
  52. // On Catalyst, the notifications can only be called on a the main thread
  53. if Thread.isMainThread {
  54. postForegroundedNotificationInternal()
  55. } else {
  56. DispatchQueue.main.sync {
  57. self.postForegroundedNotificationInternal()
  58. }
  59. }
  60. }
  61. private func postForegroundedNotificationInternal() {
  62. let notificationCenter = NotificationCenter.default
  63. #if os(iOS) || os(tvOS)
  64. notificationCenter.post(name: UIApplication.didBecomeActiveNotification, object: nil)
  65. #elseif os(macOS)
  66. notificationCenter.post(name: NSApplication.didBecomeActiveNotification, object: nil)
  67. #elseif os(watchOS)
  68. if #available(watchOSApplicationExtension 7.0, *) {
  69. notificationCenter.post(
  70. name: WKExtension.applicationDidBecomeActiveNotification,
  71. object: nil
  72. )
  73. }
  74. #endif
  75. }
  76. }