首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >本地和推送通知的Rx_Swift

本地和推送通知的Rx_Swift
EN

Stack Overflow用户
提问于 2016-04-09 02:57:47
回答 1查看 1.3K关注 0票数 0

如何在接收到本地通知和推送通知时实现observable for Local通知。在应用程序委派中,通知我们

代码语言:javascript
复制
didReceiveLocalNotification

代码语言:javascript
复制
didReceiveRemoteNotification

如何在其他屏幕上收听这些通知?我已经使用NotificationCenter来通知,但现在我想使用RX-Swift。我尝试过这种方法,但不起作用。

代码语言:javascript
复制
  extension UILocalNotification {
   var notificationSignal : Observable<UILocalNotification> {
        return Observable.create { observer in
            observer.on(.Next(self))
            observer.on(.Completed)
            return NopDisposable.instance
        }
    }
}

有谁可以帮我?

更新:

嗨,我找到了一个解决方案,使用与您使用相同的方式,但有一些变化。

代码语言:javascript
复制
class NotificationClass {
    static let bus = PublishSubject<AnyObject>()

    static func send(object : AnyObject) {
        bus.onNext(object)
    }

    static func toObservable() -> Observable<AnyObject> {
        return bus
    }

}

从AppDelegate发送通知:

代码语言:javascript
复制
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    NotificationClass.send(notification)
}

然后观察任何其他类。

代码语言:javascript
复制
    NotificationClass.bus.asObserver()
        .subscribeNext { notification in
            if let notification : UILocalNotification = (notification as! UILocalNotification) {
                print(notification.alertBody)
            }
    }
    .addDisposableTo(disposeBag)

这个类最棒的地方就是我们可以通过它发出和使用anyObject。

EN

回答 1

Stack Overflow用户

发布于 2016-04-09 05:30:25

像这样怎么样?

代码语言:javascript
复制
// 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,所以这可能不是最好的方法。然而,它是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36507262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档