2016-09-06 193 views
4

下埃尔卡皮坦编码雨燕3.0SWIFT 2.0 SWIFT 3.0 NSNotification /通知

试图从雨燕2.0在项目中的这些线转换为雨燕3.0

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

使用XCode8公测6于是我管理凑齐这...

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) 

它编译和发送,当我运行它,并建立一个监听这一行的通知,但没有用户信息,我可以解码?

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

此代码打印 “无” 在没有用户信息...

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

使用代码完成,它也揭示了一个方法,'后(名称:OBJE ct:userInfo:)'或⌘-点击'NotificationCenter'查看可用的方法。 – vadian

回答

7

正如@vadian说,NotificationCenterpost(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] 

或者,你可以提取词典在 回调像这样的(也是从上面的苹果开发者论坛线程)值:

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) 
     } 
    } 
+0

'作为NSDictionary?如? [String:Int]'很难看(我不是怪你) – vadian

+0

@vadian:是的。我苦苦挣扎了一段时间,在找到Apple Developer Forum中的解决方案之前,总是得到''[AnyHashable:Any]'不能转换为...'编译器错误。增加了一个替代品 –

+0

优秀。完美的作品! – user3069232