iPhone開發 Swift - NSNotification 通知

來源:互聯網
上載者:User

標籤:des   style   color   os   檔案   io   for   2014   

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,並添加以下方法

funcapplication(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()

}

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.