Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 简化swift通知中心事件和观察员_Ios_Swift_Notificationcenter - Fatal编程技术网

Ios 简化swift通知中心事件和观察员

Ios 简化swift通知中心事件和观察员,ios,swift,notificationcenter,Ios,Swift,Notificationcenter,我最近开始了新的swift项目。我想简化通知和通知观察员的使用,所以为此编写了一些代码。所以我想分享这段代码,并询问可能存在的问题 事件,将事件发布到通知中心的类 import Foundation enum EventName: String { case ProfileUpdate case ApplicationDidPreload } class Event { static let shared: Event = Event() /// Post

我最近开始了新的swift项目。我想简化通知和通知观察员的使用,所以为此编写了一些代码。所以我想分享这段代码,并询问可能存在的问题

事件,将事件发布到通知中心的类

import Foundation

enum EventName: String {
    case ProfileUpdate
    case ApplicationDidPreload
}

class Event {

    static let shared: Event = Event()

    /// Post event to notification center
    /// - Parameter event: event name to post
    /// - Parameter object: data you're going to pass
    /// - Parameter userInfo: user info
    func post(event: EventName, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil) {
        let notification: Notification = Notification(name: Notification.Name(rawValue: event.rawValue), object: object, userInfo: userInfo)
        NotificationCenter.default.post(notification)
    }
}
事件侦听器类,具有两个观察通知的方法。我想处理数据是否传递给通知的两种情况

import Foundation

class EventListener {

    typealias callback = () -> ()
    typealias callbackWithData = (_ data: Any) -> ()

    static let shared: EventListener = EventListener()
    private var callback: callback?
    private var callbackWithData: callbackWithData?

    /// Listen event which not return any data in callback closure
    /// Parameter event: event name to listen
    /// Parameter callback: callback closure
    func listenEvent(event: EventName, callback: @escaping callback) {
        self.callback = callback
        self.addObserver(event: event)
    }

    /// Listen event which returns data in callback closure
    /// Parameter event: event name to listen
    /// Parameter callback: callback closure
    func listenEvent(event: EventName, callbackWithData: @escaping callbackWithData) {
        self.callbackWithData = callbackWithData
        self.addObserver(event: event)
    }

    /// Add and setup observer to notification center
    private func addObserver(event: EventName) {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.handler),
                                               name: NSNotification.Name(rawValue: event.rawValue),
                                               object: nil)
    }

    /// Handle notification observer
    @objc private func handler(notification: Notification) {
        guard let data = notification.object else {
            self.callback?()
            return
        }

        self.callbackWithData?(data)
    }
}
用法示例

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            Event.shared.post(event: .ApplicationDidPreload)
            Event.shared.post(event: .ProfileUpdate, object: 1)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        EventListener.shared.listenEvent(event: .ApplicationDidPreload, callback: self.test1)
        EventListener.shared.listenEvent(event: .ProfileUpdate, callbackWithData: self.test2)
    }

    private func test1() {
        print("preloaded")
    }

    private func test2(data: Any) {
        print("profile id")
        let Id: Int? = data as? Int
        print(Id)
    }
}

如果不需要发布到通知中心的事件类,那么最好扩展通知

extension Notification.Name {
  static let MyNotificationName = Notification.Name("MyNotificationName")
}
这使您可以仅使用
.MyNotificationName
作为通知名称

要在侦听通知时使用块,还可以使用现有的基于块的观察者版本:

func addObserver(forName name: NSNotification.Name?, 
                   object obj: Any?, 
                        queue: OperationQueue?, 
                  using block: @escaping (Notification) -> Void) -> NSObjectProtocol

很高兴你想分享你的代码,但这不是一个真正的stackoverflow问题(查找可能的问题),也许会是一个更好的地方。谢谢你的建议,下次我将使用CodeReviewBest答案(Y)