0

我已经阅读了有关堆栈溢出的所有可能解决方案,但没有一个适合我。

我的代码是

func foo() {
    NotificationCenter.default.addObserver(self, selector: #selector(fetchedUser(notification:)) , name: NSNotification.Name.init("dbReady"), object: nil)
    loggedUser.fetchUserByUID(id: current.uid)    
    return true
}

func fetchedUser(notification:NSNotification){
    let info = notification.object as! [String : AnyObject]
    print(info)
}

在另一堂课上,我有:

 NotificationCenter.default.post(name: NSNotification.Name.init("dbReady"), object: dictionary)

选择器的所有语法都不起作用

我试过了:

1. fetchedUser
2. fetchedUser:
3. fetchedUser(notification:)
4. "fetchedUser:"

可能还有其他十个选项。谁能帮我?

4

5 回答 5

3

在 Swift 3 中,(系统)通知具有以下标准签名:

func notifFunction(_ notification: Notification)

所以你的功能应该是

func fetchedUser(_ notification: Notification){

而对应的选择器是

#selector(fetchedUser(_:))

为方便起见,您可以使用Notification.Name

extension Notification.Name {
  static let databaseReady = NSNotification.Name("dbReady")
}

然后你可以写

NotificationCenter.default.addObserver(self, selector: #selector(fetchedUser(_:)) , name: .databaseReady, object: nil)

NotificationCenter.default.post(name: .databaseReady, object: dictionary)
于 2016-12-01T10:27:55.557 回答
1

它适用于我的项目。

发布通知

let dic: [String:AnyObject] = ["news_id": 1 as AnyObject,"language_id" : 2 as AnyObject]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationKeyIndentifier"), object: dic)

通知观察员

在您要观察的所需类上添加以下代码。

NotificationCenter.default.addObserver(self, selector: #selector(self.handlePushNotification(notification:)), name: NSNotification.Name(rawValue: "NotificationKeyIndentifier"), object: nil)

这是通知观察者观察到后触发的函数。

func handlePushNotification(notification: NSNotification){

    if let dic = notification.object as? [String: AnyObject]{

        if let language_id = dic["language_id"] as? Int{

            if let news_id = dic["news_id"] as? Int{
                    print(language_id)
                    print(news_id)
              }
          }
      }
 }

希望它可以帮助你。如果您对此有任何问题,请填写免费提问。

于 2016-12-01T10:36:55.627 回答
0
class Observer {

    init() {
        let name = NSNotification.Name("TestNotification")
        NotificationCenter.default.addObserver(self, selector: #selector(notificationDidTrigger), name: name, object: nil)
    }

    @objc func notificationDidTrigger(notification: Notification) {
        print("Notification triggered ", notification.userInfo)
    }
}


let obj = Observer()

let name = NSNotification.Name("TestNotification")
var notification = Notification(name: name, object: nil)
notification.userInfo =  ["Name": "My notification"]
NotificationCenter.default.post(notification)
于 2016-12-01T10:36:04.010 回答
0

你可以试试这个:

NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.fetchedUser), name: notificationName, object: nil)
于 2016-12-01T10:32:36.803 回答
0

我的错误是名称不存在“fetchedUserWithNotification:”的选择器。我通过重写一个新类并复制并粘贴其所有内容来解决我的问题。也许这是一个 Xcode 错误(恕我直言,最后一个版本很多)

于 2016-12-01T11:17:13.693 回答