HXProcessNotification.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // HXProcessNotification.swift
  3. // ScreenShareExtension
  4. //
  5. // Created by Bugu on 2023/10/25.
  6. // Copyright © 2023 Bugu. All rights reserved.
  7. //
  8. import Foundation
  9. import CoreFoundation
  10. struct HXProcessNotification {
  11. static let callback: CFNotificationCallback = { (center: CFNotificationCenter?, observer: UnsafeMutableRawPointer?, name: CFNotificationName?, object: UnsafeRawPointer?, userInfo: CFDictionary?) in
  12. DispatchQueue.main.async {
  13. if let identifier = name?.rawValue as String? {
  14. NotificationCenter.default.post(name: Notification.Name(identifier), object: identifier)
  15. }
  16. }
  17. }
  18. static func addObserver(_ observer: AnyObject, selector: Selector, notificationName: String, object: Any?) {
  19. DispatchQueue.main.async {
  20. let center = CFNotificationCenterGetDarwinNotifyCenter()
  21. let pointerObserver = Unmanaged.passUnretained(observer).toOpaque()
  22. CFNotificationCenterAddObserver(center, pointerObserver, self.callback, notificationName as CFString, nil, .deliverImmediately)
  23. NotificationCenter.default.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: notificationName), object: object)
  24. }
  25. }
  26. static func removeObserver(_ observer: AnyObject, notificationName: String) {
  27. let center = CFNotificationCenterGetDarwinNotifyCenter()
  28. let pointerObserver = Unmanaged.passUnretained(observer).toOpaque()
  29. CFNotificationCenterRemoveObserver(center, pointerObserver, CFNotificationName(notificationName as CFString) , nil)
  30. NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: notificationName), object: nil)
  31. }
  32. static func removeObserver(_ observer: AnyObject) {
  33. let center = CFNotificationCenterGetDarwinNotifyCenter()
  34. let pointerObserver = Unmanaged.passUnretained(observer).toOpaque()
  35. CFNotificationCenterRemoveEveryObserver(center, pointerObserver)
  36. NotificationCenter.default.removeObserver(observer)
  37. }
  38. static func postNotificationName(_ notificationName: String, userInfo: [String : Any]?) {
  39. DispatchQueue.main.async {
  40. let center = CFNotificationCenterGetDarwinNotifyCenter()
  41. let userInfo = userInfo as CFDictionary?
  42. CFNotificationCenterPostNotification(center, CFNotificationName(notificationName as CFString), nil, userInfo, true)
  43. }
  44. }
  45. }