Swift:Notification Observer Using NSNotificationCenter

From Hawk Wiki
Revision as of 06:50, 23 March 2015 by Hall (Talk | contribs) (Listen Notification in Swift)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Listen Notification in Swift

func tweetSent(notification: NSNotification) {
    let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dictionary<String, Tweet>
}
//The colon in "tweetSent:" is not a typo. It indicates the function will take a parameter
NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetSent:", name: "newTweetNotification", object: nil) 

Send/Post Notification in Swift

var userInfo: Dictionary<String, Tweet> = ["tweet": newTweet]
NSNotificationCenter.defaultCenter().postNotificationName("newTweetNotification", object: nil, userInfo: userInfo)

Remove Notification Observer

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}