NotificationCenter 通知Key的管理
2020-08-05 本文已影响0人
啧啧同学
通过Swift的extension, 可以很方便声明及管理NotificationCenter的key
创建一个文件FCNotificationConst,专门用来存放NotificationCenter的key
/* 登录相关变化等 */
extension Notification.Name {
static let login = NSNotification.Name("com.fc.login")
static let offlineLogin = NSNotification.Name("com.fc.offline.login")
static let logout = NSNotification.Name("com.fc.logout")
static let otherLogin = NSNotification.Name("com.fc.otherLogin")
static let sessionExpired = NSNotification.Name("com.fc.sessionExpired")
}
/* 具体业务相关 */
extension NSNotification.Name {
// 切换语言
static let langSwitched = NSNotification.Name("com.fc.lang.switched")
//切换主题
static let themeSwitched = NSNotification.Name("com.fc.theme.switched")
}
使用🌰
//发送切换语言的通知
NotificationCenter.default.post(name: .langSwitched, object: nil)
//监听语言的通知
NotificationCenter.default.addObserver(self, selector: #selector(onReceivedLangSwitchedNotification(_:)), name: .langSwitched, object: nil)
@objc func onReceivedLangSwitchedNotification(_ note: Any) {
/* 接受到语言变更通知后的操作 */
}