生活随笔
收集整理的這篇文章主要介紹了
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
: { _ inprint("程序進入到后臺")})
程序進入到后臺
② 監聽鍵盤的通知
- 分別監聽虛擬鍵盤的打開和關閉通知,并在控制臺中輸出相關信息:
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
: { _ intextField
.resignFirstResponder()}).disposed(by
: disposeBag
)
_ = NotificationCenter.default.rx
.notification(NSNotification.Name.UIKeyboardWillShow).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { _ inprint("鍵盤出現")})
_ = NotificationCenter.default.rx
.notification(NSNotification.Name.UIKeyboardWillHide).takeUntil(self.rx
.deallocated
) .subscribe(onNext
: { _ inprint("鍵盤消失")})
二、自定義通知的發送與接收
- 定義一個 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
inlet userInfo
= notification
.userInfo
as! [String: AnyObject]let value1
= userInfo
["value1"] as! Stringlet value2
= userInfo
["value2"] as! Intprint("\(name) 獲取到通知,用戶數據是[\(value1),\(value2)]")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 執行完畢
通知完畢
總結
以上是生活随笔為你收集整理的RxSwift之NotificationCenter的使用和自定义的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。