{"id":2794,"date":"2016-04-19T09:14:57","date_gmt":"2016-04-19T15:14:57","guid":{"rendered":"http:\/\/dev.iachieved.it\/iachievedit\/?p=2794"},"modified":"2016-09-17T20:04:05","modified_gmt":"2016-09-18T02:04:05","slug":"nsnotifications-with-userinfo-in-swift-2-2","status":"publish","type":"post","link":"https:\/\/dev.iachieved.it\/iachievedit\/nsnotifications-with-userinfo-in-swift-2-2\/","title":{"rendered":"NSNotifications with userInfo in Swift 2.2"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/img.shields.io\/badge\/Xcode-7.3-blue.svg?style=flat\" alt=\"Xcode 7.3\" \/> <img decoding=\"async\" src=\"https:\/\/img.shields.io\/badge\/Swift-2.2-orange.svg?style=flat\" alt=\"Swift 2.2\" \/><\/p>\n<p>Looking for help using notifications with Swift 3.0?  Head on over <a href=\"http:\/\/dev.iachieved.it\/iachievedit\/notifications-and-userinfo-with-swift-3-0\/\">here<\/a> where we go over the latest Swift 3.0 changes.<\/p>\n<p>When I sit down to blog I never know what will be a popular topic and what won&#8217;t.  One that definitely surprised me was how popular the original <a href=\"http:\/\/dev.iachieved.it\/iachievedit\/nsnotifications-with-userinfo-in-swift\/\">NSNotifications with userInfo in Swift<\/a> would end up being.  Much has changed since Swift first hit the scenes, so I thought we&#8217;d provide an update to handling <code>NSNotification<\/code> <code>userInfo<\/code> and some working code to help out.<\/p>\n<p>The technique for obtaining the default <code>NSNotificationCenter<\/code> has remained unchanged, and can be done with <code>let nc = NSNotificationCenter.defaultCenter()<\/code>.  What <i>has changed<\/i> in the latest versions of Swift is how to specify the <i>selector<\/i> (i.e., the function that should be called when a notification has posted).  Rather than using a bare string like <code>\"catchNotification\"<\/code>, Xcode will instruct you to use the <code>#selector<\/code> directive, like this:<\/p>\n<pre class=\"lang:swift\">\nlet nc = NSNotificationCenter.defaultCenter()\nnc.addObserver(self, \n               selector: #selector(ViewController.catchNotification),\n               name: \"MyNotification\", \n               object: nil)\n<\/pre>\n<p>In this example we&#8217;re instructing the notification center to deliver <code>MyNotification<\/code> notifications to the <code>catchNotification<\/code> function of the <code>ViewController<\/code> class.<\/p>\n<h3>Post It!<\/h3>\n<p>Now, let&#8217;s look at <i>posting<\/i> (sending) a notification:<\/p>\n<pre class=\"lang:swift\">\nlet nc = NSNotificationCenter.defaultCenter()\nnc.postNotificationName(\"MyNotification\",\n                        object: nil,\n                        userInfo: [\"message\":\"Hello there!\", \"date\":NSDate()])\n<\/pre>\n<p>The <code>userInfo<\/code> still takes <code>[NSObject : AnyObject]?<\/code> as an argument, which we provide as a dictionary literal in Swift.  Note that the <code>userInfo<\/code> values don&#8217;t need to be homogeneous (that&#8217;s where the <code>AnyObject<\/code> comes in); we are sending along a <code>String<\/code> and an <code>NSDate<\/code>.<\/p>\n<h3>Handling Notifications<\/h3>\n<p>The <code>guard<\/code> construct did not exist in Swift when I wrote the original code used to pull apart the <code>userInfo<\/code> data, but it serves as a good method to unwrap and verify that the expected data is in the <code>userInfo<\/code>.<\/p>\n<pre class=\"lang:swift\">\n  func catchNotification(notification:NSNotification) -> Void {\n    print(\"Catch notification\")\n    \n    guard let userInfo = notification.userInfo,\n          let message  = userInfo[\"message\"] as? String,\n          let date     = userInfo[\"date\"]    as? NSDate else {\n      print(\"No userInfo found in notification\")\n      return\n    }\n    \n    let alert = UIAlertController(title: \"Notification!\",\n                                  message:\"\\(message) received at \\(date)\",\n                                  preferredStyle: UIAlertControllerStyle.Alert)\n    alert.addAction(UIAlertAction(title: \"OK\", style: UIAlertActionStyle.Default, handler: nil))\n    self.presentViewController(alert, animated: true, completion: nil)\n    \n  }\n<\/pre>\n<p>To verify that the <code>guard<\/code> works properly switch out the <code>NSDate()<\/code> in the call to <code>postNotificationName<\/code> with a <code>String<\/code> or some other object.  You should see <code>No userInfo found in notification<\/code> printed to the console.<\/p>\n<h3>Example Source<\/h3>\n<p>You can try out the code above with a simple iOS project.  Create a new <b>Single View Application<\/b> and replace the contents of <code>ViewController.swift<\/code> with the following:<\/p>\n<pre class=\"lang:swift\">\nimport UIKit\n\nclass ViewController: UIViewController {\n  \n  override func viewDidLoad() {\n    super.viewDidLoad()\n    \n    let nc = NSNotificationCenter.defaultCenter()\n    nc.addObserver(self,\n                   selector: #selector(ViewController.catchNotification),\n                   name: \"MyNotification\",\n                   object: nil)\n    \n  }\n  \n  override func viewDidAppear(animated: Bool) {\n    super.viewDidAppear(animated)\n    let nc = NSNotificationCenter.defaultCenter()\n    nc.postNotificationName(\"MyNotification\",\n                            object: nil,\n                            userInfo: [\"message\":\"Hello there!\",\n                                       \"date\":NSDate()])\n  }\n  \n  func catchNotification(notification:NSNotification) -> Void {\n    print(\"Catch notification\")\n    \n    guard let userInfo = notification.userInfo,\n          let message  = userInfo[\"message\"] as? String,\n          let date     = userInfo[\"date\"]    as? NSDate else {\n        print(\"No userInfo found in notification\")\n        return\n    }\n    \n    let alert = UIAlertController(title: \"Notification!\",\n                                  message:\"\\(message) received at \\(date)\",\n                                  preferredStyle: UIAlertControllerStyle.Alert)\n    alert.addAction(UIAlertAction(title: \"OK\", style: UIAlertActionStyle.Default, handler: nil))\n    self.presentViewController(alert, animated: true, completion: nil)\n  }\n}\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Looking for help using notifications with Swift 3.0? Head on over here where we go over the latest Swift 3.0 changes. When I sit down to blog I never know what will be a popular topic and what won&#8217;t. One that definitely surprised me was how popular the original NSNotifications with userInfo in Swift would [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2826,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-2794","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2794"}],"collection":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/comments?post=2794"}],"version-history":[{"count":11,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2794\/revisions"}],"predecessor-version":[{"id":2825,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2794\/revisions\/2825"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media\/2826"}],"wp:attachment":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media?parent=2794"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/categories?post=2794"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/tags?post=2794"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}