Skip to content

Instantly share code, notes, and snippets.

@squarefrog
Last active August 29, 2015 14:19
Show Gist options
  • Save squarefrog/8194e7f2c8e1b2a466fc to your computer and use it in GitHub Desktop.
Save squarefrog/8194e7f2c8e1b2a466fc to your computer and use it in GitHub Desktop.
Notification Demo
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: "bacon", object: nil)
var url = NSURL(string: "ashdfhfd")
// CRASH! Adding the bang (!) forces swift to unwrap the value. If it
// unwraps and discovers a nil you get a crash.
// println("\(url?.host!)")
url = NSURL(string: "http//google.com")!
// Instead, unwrap the optional. If the host is nil, then it'll just
// skip over this code
if let host = url?.host {
let userInfo: NSDictionary = ["myKey" : host]
NSNotificationCenter.defaultCenter().postNotificationName("bacon", object: nil, userInfo: userInfo as [NSObject : AnyObject])
}
}
// Make sure you remove your observer when you're done
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func notificationReceived(notification: NSNotification) {
if let message: AnyObject = notification.userInfo?["myKey"] {
println("Zaid \(message)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment