|
| 1 | +```swift |
| 2 | + |
| 3 | +class ViewController: UIViewController { |
| 4 | + |
| 5 | + override func awakeFromNib() { |
| 6 | + super.awakeFromNib() |
| 7 | + NotificationCenter.default.addObserver(self, selector: #selector(customFunction), name: .eventName, object: nil) |
| 8 | + } |
| 9 | + |
| 10 | + func customFunction(_ notification: Notification){ |
| 11 | + //Notification handler is able to have one parameter. |
| 12 | + //Notification instance has a userInfo. |
| 13 | + guard let myValue = notification.userInfo?["myKey"] as? String else { return } |
| 14 | + |
| 15 | + print("customEvent !!!"); |
| 16 | + print(myValue) |
| 17 | + |
| 18 | + } |
| 19 | + |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +```swift |
| 24 | + |
| 25 | +extension Notification.Name { |
| 26 | + static var eventName: Notification.Name { // in extension, there is not stored properties |
| 27 | + return Notification.Name.init("eventName") |
| 28 | + } |
| 29 | + |
| 30 | +// static var customFunction: Notification.Name { return .init("customFunction") } |
| 31 | + |
| 32 | +} |
| 33 | + |
| 34 | +class AnotherViewController: UIViewController { |
| 35 | + |
| 36 | + @IBAction func didMoveBackButtonTap() { |
| 37 | + self.dismiss(animated: true, completion: nil) |
| 38 | + } |
| 39 | + |
| 40 | + @IBAction func didNotificationButtonTap() { |
| 41 | + NotificationCenter.default.post(name: .eventName, object: self, userInfo: ["myKey": "myValue@@@"]) |
| 42 | + |
| 43 | + //NSNotification.Name is an inner struct in extension NSNotification |
| 44 | + //NotificationCenter.default.post(name: .UIApplicationDidEnterBackground, object: nil, userInfo: nil) |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
0 commit comments