之前發(fā)送通知是這樣的:
NSNotificationCenter.defaultCenter().post("NSNotificationString")
在swift3中改成了Notification.Name
extension NSNotification {
public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
使用起來(lái)感覺更麻煩了帅刀,如下:
NotificationCenter.default.post(Notification.Name(rawValue: "NSNotificationString"))
為了使用方便在很長(zhǎng)一段時(shí)間我都是通過(guò)extension聲明一個(gè)靜態(tài)的常量來(lái)使用的:
extension Notification.Name {
static let TestNotificationString = Notification.Name("NSNotificationString")
}
// 發(fā)送通知
NotificationCenter.default.post(.TestNotificationString)
但是這種方式不能有效的避免命名重復(fù)問(wèn)題奠蹬,如果命名不規(guī)范還是存在潛在的風(fēng)險(xiǎn)躲履。所以感謝網(wǎng)友的點(diǎn)子方库,通過(guò)枚舉來(lái)實(shí)現(xiàn),規(guī)避掉命名的沖突骑歹。
enum DHNotification: String {
case userLogout
case userLogin
var stringValue: String {
return "DH" + rawValue
}
var notificationName: NSNotification.Name {
return NSNotification.Name(stringValue)
}
}
使用起來(lái)就簡(jiǎn)單了历葛,實(shí)現(xiàn)一個(gè)擴(kuò)展方法:
extension NotificationCenter {
static func post(customeNotification name: DHNotification, object: Any? = nil){
NotificationCenter.default.post(name: name.notificationName, object: object)
}
}
使用方法如下:
NotificationCenter.post(customeNotification: .userLogin)
這樣是不是很簡(jiǎn)單明了。
處理通知就使用RxSwift的方式實(shí)現(xiàn)当纱,也需要擴(kuò)展一下:
extension Reactive where Base: NotificationCenter {
func notification(custom name: DHNotification, object: AnyObject? = nil) -> Observable<Notification> {
return notification(name.notificationName, object: object)
}
}
使用如下:
NotificationCenter.default.rx.notification(custom: .userLogin).subscribe(onNext: { (value) in
print(value)
TipsView.shared.showTips(info: "收到通知")
}).disposed(by: dispose)
NotificationCenter.post(customeNotification: .userLogin)
打印的信息如下:
“name = DHuserLogin, object = nil, userInfo = nil”