RxSwiftNotificationCenter的使用和自定义

网友投稿 859 2022-05-28

一、系统通知的注册与响应

① 监听应用进入后台的通知

现有如下需求:程序编译运行后,当按下设备的 home 键,程序进入后台的同时会在控制台中输出相关信息。

程序进入后台时除了会执行 AppDelegate.swift 里的 applicationDidEnterBackground 方法外,还会发送 UIApplicationDidEnterBackground 通知,这里可以使用 NotificationCenter 的 Rx 扩展方法来监听这个通知。

关于 .takeUntil(self.rx.deallocated):它的作用是保证页面销毁的时候自动移除通知注册,避免内存浪费或出现奔溃。

RxSwift之NotificationCenter的使用和自定义

// 监听应用进入后台通知 _ = NotificationCenter.default.rx .notification(NSNotification.Name.UIApplicationDidEnterBackground) .takeUntil(self.rx.deallocated) // 页面销毁自动移除通知监听 .subscribe(onNext: { _ in print("程序进入到后台") })

1

2

3

4

5

6

7

运行结果:

程序进入到后台

1

② 监听键盘的通知

分别监听虚拟键盘的打开和关闭通知,并在控制台中输出相关信息:

// 添加文本输入框 let textField = UITextField(frame: CGRect(x:20, y:100, width:200, height:30)) textField.borderStyle = .roundedRect textField.returnKeyType = .done self.view.addSubview(textField) // 点击键盘上的完成按钮后,收起键盘 textField.rx.controlEvent(.editingDidEndOnExit) .subscribe(onNext: { _ in // 收起键盘 textField.resignFirstResponder() }) .disposed(by: disposeBag) // 监听键盘弹出通知 _ = NotificationCenter.default.rx .notification(NSNotification.Name.UIKeyboardWillShow) .takeUntil(self.rx.deallocated) // 页面销毁自动移除通知监听 .subscribe(onNext: { _ in print("键盘出现") }) // 监听键盘隐藏通知 _ = NotificationCenter.default.rx .notification(NSNotification.Name.UIKeyboardWillHide) .takeUntil(self.rx.deallocated) // 页面销毁自动移除通知监听 .subscribe(onNext: { _ in print("键盘消失") })

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

二、自定义通知的发送与接收

定义一个 MyObserver.swift(观察者在收到通知后的执行的处理函数中,添加了个 3 秒的等待),如下:

class MyObserver: NSObject { var name:String = "" init(name:String){ super.init() self.name = name // 接收通知: let notificationName = Notification.Name(rawValue: "DownloadImageNotification") _ = NotificationCenter.default.rx .notification(notificationName) .takeUntil(self.rx.deallocated) // 页面销毁自动移除通知监听 .subscribe(onNext: { notification in // 获取通知数据 let userInfo = notification.userInfo as! [String: AnyObject] let value1 = userInfo["value1"] as! String let value2 = userInfo["value2"] as! Int print("\(name) 获取到通知,用户数据是[\(value1),\(value2)]") // 等待3秒 sleep(3) print("\(name) 执行完毕") }) } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

发出一个携带有自定义数据的通知,同时创建两个观察者来接收这个通知:

let observers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")] print("发送通知") let notificationName = Notification.Name(rawValue: "DownloadImageNotification") NotificationCenter.default.post(name: notificationName, object: self, userInfo: ["value1":"Kody", "value2" : 123]) print("通知完毕")

1

2

3

4

5

6

7

运行结果如下,可以看出,通知发送后的执行是同步的,也就是说观察者全部处理完毕后,主线程才继续往下进行:

发送通知 观察器1 获取到通知,用户数据是[Kody,123] 观察器1 执行完毕 观察器2 获取到通知,用户数据是[Kody,123] 观察器2 执行完毕 通知完毕

1

2

3

4

5

6

控制台

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:避坑指南:关于SPDK问题分析过程
下一篇:11.6 Linux修改用户(群组)的磁盘配额(edquota命令)
相关文章