iPhone开发 Swift - NSNotification 通知
Swift创建Notification通知
- 创建一个SingleView Application
- 打开AppDelegate.swift,在方法
application(application:UIApplication,didFinishLaunchingWithOptions launchOptions: NSDictionary?)
中输入代码:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
//设置Notification 的类型
let types:UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
//设置Notification的设置项,其中categories参数用来设置Notification的类别
let mySettings: UIUserNotificationSettings = UIUserNotificationSettings(forType: types, categories: nil);
//注册UserNotification
UIApplication.sharedApplication().registerUserNotifiationSettings(mySettings)
return true
}
- 配置不同的Actions,在方法
application(application:UIApplication,didFinishLaunchingWithOptions launchOptions: NSDictionary?)内的代码开始部分输入以下代码
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
//define Actions
var firstAction: UIMutableUserNotificationAction = UIMutableUserNotificationAction();
// The unique identifier for this action
fistAction.identifier = “FIRST_ACTION”;
// The localized title to display for this action
firstAction.title = “First Action”;
//define action’s activationMode, // How the application should be activated in response to the action
firstAction.activationMode = UIUserNotificationActivationMode.Background// 当点击的时候不启动程序,在后台处理
//define action’s destructive // Whether this action should be indicated as destructive when displayed.
firstAction.destructive = true
//define authentication // Whether this action is secure and should require unlocking before being performed. If the activation mode is UIUserNotificationActivationModeForeground, then the action is considered secure and this property is ignored.
firstAction.authenticationRequired = false//不需要用户解锁手机即可以处理该Notification
var secondAction:UIMutableUserNotificationAction = UIMutableUserNotificationAction()
secondAction.identifier = "SECOND_ACTION";
secondAction.title = "Second Action";
secondAction.activationMode = UIUserNotificationActivationMode.Foreground
secondAction.destructive = false
secondAction.authenticationRequired = false
var thirdAction:UIMutableUserNotificationAction = UIMutableUserNotificationAction()
thirdAction.identifier = "THIRD_ACTION";
thirdAction.title = "Third Action";
thirdAction.activationMode = UIUserNotificationActivationMode.Background
thirdAction.destructive = false
thirdAction.authenticationRequired = false
//Category
var firstCategory: UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
firstCategory.identifier = "FIRST_CATEGORY";
let defaultActions:NSArray = [firstAction, secondAction, thirdAction];
let minimalActions:NSArray = [firstAction, secondAction];
// Sets the UIUserNotificationActions in the order to be displayed for the specified context
firstCategory.setActions(defaultActions, forContext: UIUserNotificationActionContext.Default);// // the default context of a notification action
firstCategory.setActions(minimalActions, forContext: UIUserNotificationActionContext.Minimal);//Minimal // the context of a notification action when space is limited
let categories: NSSet = NSSet(objects: firstCategory)
//设置Notification 的类型
let types:UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
//设置Notification的设置项,其中categories参数用来设置Notification的类别
let mySettings: UIUserNotificationSettings = UIUserNotificationSettings(forType: types, categories: nil);
//注册UserNotification
UIApplication.sharedApplication().registerUserNotifiationSettings(mySettings)
return true
}
4. 打开ViewController.swift文件,在ViewDidLoad方法中输入以下代码
override func viewDidLoad() {
super.viewDidLoad()
//define notification center
NSNotificationCenter.defaultCenter().addObserver(self, selector: “TestShape:”, name: “actionOne”, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:”TestMessage:”, name: “actionTwo”, object: nil)
//定义一个触发Notification的程序
var dateComp: NSDateComponents =
NSDateComponents()
dateComp.year = 2014
dateComp.month = 09
dateComp.day = 09
dateComp.hour = 11
dateComp.minute = 11
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calendar: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var date: NSDate = calendar.dateFromComponents(dateComp)
//define Location notification
var notification: UILocalNotification = UILocalNotification()
notification.category = “FIRST_CATEGORY”;
notification.alertBody = “This is a notification”
notification.fireDate = date
//fire notification
UIApplication.shareApplication().scheduleLocalNotification(notification)
}
func TestShape(notification: NSNotification) {
UIView *view = UIView(frame: CGRectMake(100,100,100,100));
view.backgroundColor = UIColor.blackColor()
Self.view.addSubview(view)
}
func TestMessage(notification: NSNotification) {
var message: UIAlertController = UIAlertController(title: “Notification Message”, message: “Hello, this is an alert message”, preferredStyle: UIAlertControllerStyle.Alert)
message.addAction(UIAlertAction(title: “OK”, style: UIAlertActionStyle.Default, handle: nil))
self.presentViewController(message, animated: true, completion: nil)
}
5. 回到AppDelegate.swift,并添加以下方法
func application(application: UIApplication!, handleActionWithIdentifier identifier: String!, forLocalNotification notification: UILocalNotification!, completionHandler: (() -> Void)!) {
if identifier == “FIRST_ACTION” {
NSNotificationCenter.defaultCenter().postNotificationName(“actionOne”, object: nil)
}
else if identifier == “SECOND_ACTION” {
NSNotificationCenter.defaultCenter().postNotificationName(“actionTwo”, object: nil)
}
completionHandler()
}