NSNotificationCenter.defaultCenter().addObserver(<#observer: AnyObject#>, selector: <#Selector#>, name: <#String?#>, object: <#AnyObject?#>)
NSNotificationCenter.defaultCenter().addObserver(self自己就是观察者, selector: ""选择处理通知的方法(接收通知的方法), name: ""通知的名字, object: nil对象为空)
下面红色标注部分是错的部分
import UIKit
class ViewController: UIViewController {
@IBAction func onClick(sender: AnyObject) {
var resViewController = self.storyboard?.instantiateViewControllerWithIdentifier("navViewController") as UINavigationController
self.presentViewController(resViewController, animated: true ) { () -> Void in
NSLog("弹出模态视图")
}
}
//主要是方法后面没有加上冒号,接收通知的是一个方法,需要加上冒号,不加冒号表示字符串。
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "registerCompletion:",
name: "RegisterCompletionNotification", object: nil)
//监听系统通知
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "handleEnterBackground:",
name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "handleEnterForeground:",
name: UIApplicationWillEnterForegroundNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//TODO接收通知
func registerCompletion(notification : NSNotification) {
let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
let username = userInfo["username"]!
NSLog("username = %@",username)
}
func handleEnterBackground(notification : NSNotification) {
NSLog("进入到后台")
}
func handleEnterForeground(notification : NSNotification) {
NSLog("回到前台")
}
}