iPhone開發 Swift - NSNotification 通知


Swift創建Notification通知

  1. 創建一個SingleView Application
  2. 打開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

}

  1. 配置不同的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()

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM