RxSwift之NotificationCenter的使用和自定义

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

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

  • 现有如下需求:程序编译运行后,当按下设备的 home 键,程序进入后台的同时会在控制台中输出相关信息。
  • 程序进入后台时除了会执行 AppDelegate.swift 里的 applicationDidEnterBackground 方法外,还会发送 UIApplicationDidEnterBackground 通知,这里可以使用 NotificationCenter 的 Rx 扩展方法来监听这个通知。
  • 关于 .takeUntil(self.rx.deallocated):它的作用是保证页面销毁的时候自动移除通知注册,避免内存浪费或出现奔溃。
// 监听应用进入后台通知
_ = NotificationCenter.default.rx
    .notification(NSNotification.Name.UIApplicationDidEnterBackground)
    .takeUntil(self.rx.deallocated)  // 页面销毁自动移除通知监听
    .subscribe(onNext: {
    
     _ in
        print("程序进入到后台")
    })
  • 运行结果:
程序进入到后台

② 监听键盘的通知

  • 分别监听虚拟键盘的打开和关闭通知,并在控制台中输出相关信息:
// 添加文本输入框
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("键盘消失")
    })

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

  • 定义一个 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) 执行完毕")
            })
    }
}
  • 发出一个携带有自定义数据的通知,同时创建两个观察者来接收这个通知:
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 获取到通知,用户数据是[Kody,123]
观察器1 执行完毕
观察器2 获取到通知,用户数据是[Kody,123]
观察器2 执行完毕
通知完毕

Guess you like

Origin blog.csdn.net/Forever_wj/article/details/121309391