Last active
August 29, 2015 14:19
-
-
Save squarefrog/8194e7f2c8e1b2a466fc to your computer and use it in GitHub Desktop.
Notification Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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