Swift 2到Swift 3 NSNotification / Notification

时间:2016-09-06 14:40:39

标签: swift notifications

XCode 8 beta 6

中的El Capitan编码下使用Swift 3.0

尝试将项目中的这些行从Swift 2.0转换为Swift 3.0

let userInfo = ["peer": peerID, "state": state.toRaw()]
NSNotificationCenter.defaultCenter.postNotificationName("Blah", object: nil, userInfo: userInfo)

所以我设法凑齐了......

public class MyClass {
    static let myNotification = Notification.Name("Blah")
    }

let userInfo = ["peerID":peerID,"state":state.rawValue] as [String : Any]
NotificationCenter.default.post(name: MyClass.myNotification, object: userInfo)

它在我运行它时编译并发送通知并使用此行设置一个监听器,但没有我可以解码的userInfo?

 let notificationName = Notification.Name("Blah")
    NotificationCenter.default.addObserver(self, selector: #selector(peerChangedStateWithNotification), name: notificationName, object: nil)

此代码打印" nil"就像没有userInfo ...

func peerChangedStateWithNotification(notification:NSNotification) {
    print("\(notification.userInfo)")
}

1 个答案:

答案 0 :(得分:7)

正如@vadian所说,NotificationCenter有一个 您可以使用的post(name:object:userInfo:)方法。

这是一个自包含的示例,它也演示了如何 将userInfo转换回预期类型的​​字典 (取自https://forums.developer.apple.com/thread/61578):

class MyClass: NSObject {
    static let myNotification = Notification.Name("Blah")

    override init() {
        super.init()

        // Add observer:
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(notificationCallback),
                                               name: MyClass.myNotification,
                                               object: nil)

        // Post notification:
        let userInfo = ["foo": 1, "bar": "baz"] as [String: Any]
        NotificationCenter.default.post(name: MyClass.myNotification,
                                        object: nil,
                                        userInfo: userInfo)
    }

    func notificationCallback(notification: Notification) {
        if let userInfo = notification.userInfo as? [String: Any] {
            print(userInfo)
        }
    }
}

let obj = MyClass()
// ["bar": baz, "foo": 1]

或者,您可以在中提取字典值 像这样的回调(也来自Apple Developer Forum主题):

    func notificationCallback(notification: Notification) {
        guard let userInfo = notification.userInfo else { return }
        if let fooValue = userInfo["foo"] as? Int {
            print("foo =", fooValue)
        }
        if let barValue = userInfo["bar"] as? String {
            print("bar =", barValue)
        }
    }