如何在接收到本地通知和推送通知时实现observable for Local通知。在应用程序委派中,通知我们
didReceiveLocalNotification和
didReceiveRemoteNotification如何在其他屏幕上收听这些通知?我已经使用NotificationCenter来通知,但现在我想使用RX-Swift。我尝试过这种方法,但不起作用。
extension UILocalNotification {
var notificationSignal : Observable<UILocalNotification> {
return Observable.create { observer in
observer.on(.Next(self))
observer.on(.Completed)
return NopDisposable.instance
}
}
}有谁可以帮我?
更新:
嗨,我找到了一个解决方案,使用与您使用相同的方式,但有一些变化。
class NotificationClass {
static let bus = PublishSubject<AnyObject>()
static func send(object : AnyObject) {
bus.onNext(object)
}
static func toObservable() -> Observable<AnyObject> {
return bus
}
}从AppDelegate发送通知:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
NotificationClass.send(notification)
}然后观察任何其他类。
NotificationClass.bus.asObserver()
.subscribeNext { notification in
if let notification : UILocalNotification = (notification as! UILocalNotification) {
print(notification.alertBody)
}
}
.addDisposableTo(disposeBag)这个类最棒的地方就是我们可以通过它发出和使用anyObject。
发布于 2016-04-09 05:30:25
像这样怎么样?
// this would really be UILocalNotification
struct Notif {
let message: String
}
class MyAppDelegate {
let localNotification = PublishSubject<Notif>()
// this would really be `application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)`
func didReceiveLocalNotification(notif: Notif) {
localNotification.on(.Next(notif))
}
}
let appDelegate = MyAppDelegate() // this singleton would normally come from `UIApplication.sharedApplication().delegate`
class SomeClassA {
let disposeBag = DisposeBag()
init() {
appDelegate.localNotification
.subscribe { notif in
print(notif)
}
.addDisposableTo(disposeBag)
}
}
let a = SomeClassA()
appDelegate.didReceiveLocalNotification(Notif(message: "notif 1"))
let b = SomeClassA()
appDelegate.didReceiveLocalNotification(Notif(message: "notif 2"))我还在学习RxSwift,所以这可能不是最好的方法。然而,它是有效的。
https://stackoverflow.com/questions/36507262
复制相似问题