一. application: didReceiveLocalNotification: notification:
- 該方法的調用時間
- 該方法是App接收到通知的時候調用的
- 如果App在前臺的時候接到通知, 會調用此方法執(zhí)行一些操作, 但是不會有推送通知的提示
- 如果App在后臺的時候接到通知, 那么會在點擊通知, App從后臺轉移到前臺的時候調用這個方法
- 但是, 如果App已經(jīng)退出了, 那么接到本地通知, 點擊通知從后臺跳轉到前臺的時候, 就不會調用這個方法
- 該方法的使用注意點
- 通過application的運行周期屬性
application.applicationState
, 來執(zhí)行一些操作 - 當App處于前臺的時候, 使用
.Active
來執(zhí)行一些操作 - 當App從前臺跳轉到后臺的時候, 使用
.Inactive
來執(zhí)行一些操作 - 注意, 此方法當App完全退出之后, 不會調用
- 通過application的運行周期屬性
二. 在申請授權的時候執(zhí)行額外操作
-
為通知創(chuàng)建操作組(categories)
在iOS8.0之后, 如果要使用本地通知, 就必須先注冊這個本地通知, 然后才能使用
在注冊時, 可以為通知設置很多詳細的屬性, 其中一個就是通知的操作行為
操作行為, 會在你的App處于后臺時, 當他接到通知, 你的通知會多出兩個額外的按鈕, 這兩個按鈕就是操作組的action
操作行為可以詳細設置為前臺觸發(fā), 后臺觸發(fā)
-
操作行為必須有一個組標識, 這樣在你發(fā)送這個通知的時候, 才能發(fā)送出有標識的這個通知
// 申請通知授權 func localNotificationAuthority() { if #available(iOS 8.0, *) { // 創(chuàng)建通知類型 let typeValue = UIUserNotificationType.Alert.rawValue | UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Sound.rawValue let type = UIUserNotificationType(rawValue: typeValue) // 創(chuàng)建一個操作組 let category : UIMutableUserNotificationCategory = UIMutableUserNotificationCategory() // 設置組標識 category.identifier = "select" // 添加組行為 let action1 = UIMutableUserNotificationAction() action1.identifier = "action1" action1.title = "action1" // 操作行為的環(huán)境條件 // Foreground: 當用戶點擊了這個行為, 必須進入到前臺才能執(zhí)行 // Background: 當用戶點擊了這個行為, 在后臺也可以執(zhí)行 action1.activationMode = .Foreground action1.destructive = false // 通過顏色來標識這個行為 // 創(chuàng)建第二個組行為 let action2 = UIMutableUserNotificationAction() action2.identifier = "action2" action2.title = "action2" action2.activationMode = .Background action2.authenticationRequired = true // 是否在解鎖屏幕之后才能執(zhí)行, 如果activation為前臺, 此屬性會被忽略 action2.destructive = true // 在iOS9.0之后, 通知是可以綁定一些操作行為的 if #available(iOS 9.0, *) { action2.behavior = .TextInput action2.parameters = [UIUserNotificationTextInputActionButtonTitleKey: "回復"] } // 創(chuàng)建操作數(shù)組 let actions : [UIUserNotificationAction] = [action1, action2] // 設置操作組 // 參數(shù)1: 操作行為數(shù)組 // 參數(shù)2: 通知行為的上下文, 作用在彈窗的樣式 // Default: 最多可以有四個行為; Minimal: 如果空間不夠, 最多只有兩個行為 category.setActions(actions, forContext: UIUserNotificationActionContext.Default) // 創(chuàng)建操作選項組 let categories : Set<UIUserNotificationCategory> = [category] let setting = UIUserNotificationSettings(forTypes: type, categories: categories) UIApplication.sharedApplication().registerUserNotificationSettings(setting) }
-
點擊操作組會觸發(fā)的方法
當用戶點擊了本地通知的某個操作行為時會調用這個方法
可以根據(jù)操作的標識, 判斷用戶點擊了哪個按鈕, 以做出不同的操作
-
一定要調用系統(tǒng)提供的回調函數(shù)
// 當用戶點擊了本地通知的某個行為時調用 func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if identifier == "action1" { print("點擊了action1") } else if identifier == "action2" { print("點擊了action2") } // 注意要調用系統(tǒng)回調的block completionHandler() }