Swift - 异步编程库PromiseKit使用详解3(NotificationCenter的扩展)
作者:hangge | 2018-12-07 08:10
四、NotificationCenter 扩展
1,准备工作
我们同样要安装 PromiseKit 库,以及相关的 PMKFoundation 扩展库,具体步骤参考我之前的文章:
2,系统通知的监听和响应
(1)当程序启动后,按下设备的 home 键进入后台时,会发送个 UIApplication.didEnterBackgroundNotification 通知。下面我们监听这个通知并在控制台输出相关信息:
注意:通知响应后,PromiseKit 会自动将相应的通知注册给取消,也就是说每个监听通知都是一次性的。为了让通知能被反复多次监听,这里在响应后继续调用方法进行观察。
import UIKit
import PromiseKit
import PMKFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//开始监听通知
beginObserve()
}
//开始监听通知
func beginObserve() {
//监听程序进入后台的通知
NotificationCenter.default.observe(once:
UIApplication.didEnterBackgroundNotification).done { notification in
print("程序进入到后台了")
//继续接听通知
self.beginObserve()
}
}
}
(2)下面代码分别监听虚拟键盘的打开和关闭通知,并在控制台中输出相关信息。
//监听键盘弹出通知
NotificationCenter.default.observe(once:
UIResponder.keyboardWillShowNotification).done { notification in
print("键盘出现了")
}
//监听键盘隐藏通知
NotificationCenter.default.observe(once:
UIResponder.keyboardWillHideNotification).done { notification in
print("键盘消失了")
}
3,自定义通知的发送与接收
通知类型其实就是一个字符串,所以我们也可以使用自己定义的通知(同时还可以传递用户自定义数据)。
(1)ViewController.swift(我们发出一个携带有自定义数据的通知,同时创建两个观察者来接收这个通知。)
import UIKit
import PromiseKit
import PMKFoundation
class ViewController: UIViewController {
let observers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")]
override func viewDidLoad() {
super.viewDidLoad()
print("发送通知")
let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
NotificationCenter.default.post(name: notificationName, object: self,
userInfo: ["value1":"hangge.com", "value2" : 12345])
print("通知发送完毕")
}
}
(2)MyObserver.swift(观察者在收到通知后的执行的处理函数中,添加了个 3 秒的等待。)
import UIKit
import PromiseKit
import PMKFoundation
class MyObserver: NSObject {
var name:String = ""
init(name:String){
super.init()
self.name = name
//开始观察
beginObserver()
}
//开始观察
func beginObserver() {
let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
NotificationCenter.default.observe(once: notificationName).done { notification in
let userInfo = notification.userInfo as! [String: AnyObject]
let value1 = userInfo["value1"] as! String
let value2 = userInfo["value2"] as! Int
print("\(self.name) 获取到通知,用户数据是[\(value1),\(value2)]")
sleep(3)
print("\(self.name) 执行完毕")
//继续观察
self.beginObserver()
}
}
}
(3)运行结果如下。可以看出,通知发送后,观察者执行是同步的(一个执行完毕后才执行另一个)。
全部评论(0)