UILocalNotification 總結
//
// AppDelegate.swift
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
print("\n\t didFinishLaunchingWithOptions \(launchOptions) ")
//iOS8.0 注冊推送通知
if #available(iOS 8.0, *) {
//1.創建一組動作
let userAction = UIMutableUserNotificationAction()
userAction.identifier = "action1"
userAction.title = "Accept"
userAction.activationMode = UIUserNotificationActivationMode.Foreground
let userAction2 = UIMutableUserNotificationAction()
userAction2.identifier = "action2"
userAction2.title = "Ingore"
userAction2.activationMode = UIUserNotificationActivationMode.Background
userAction2.authenticationRequired = true
userAction2.destructive = true
//2.創建動作的類別集合
let userCategory = UIMutableUserNotificationCategory()
userCategory.identifier = "MyNotification"
userCategory.setActions([userAction,userAction2], forContext: UIUserNotificationActionContext.Minimal)
let categories:NSSet = NSSet(object: userCategory)
//3.創建UIUserNotificationSettings,并設置消息的顯示類類型
let userSetting = UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge, categories: categories as? Set<UIUserNotificationCategory>)
//4.注冊推送
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(userSetting)
} else {
// Fallback on earlier versions
UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge)
}
if (launchOptions != nil) {
let badge = UIApplication.sharedApplication().applicationIconBadgeNumber
if badge>0{
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
}
return true
}
//當App既將進入后臺、鎖屏、有電話進來時會觸發此事件
func applicationWillResignActive(application: UIApplication) {
print("\n\t applicationWillResignActive ")
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
//當App進入后臺時觸發此事件
func applicationDidEnterBackground(application: UIApplication) {
print("\n\t applicationDidEnterBackground ")
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//清除所有本地推送
UIApplication.sharedApplication().cancelAllLocalNotifications()
//初始化本地通知對象
let notification = UILocalNotification()
//設置通知的提醒時間
// var currentDate:NSDate = NSDate()
// notification.fireDate = currentDate.dateByAddingTimeInterval(5.0)
//設置推送使用本地時區
notification.timeZone = NSTimeZone.localTimeZone()
//設置重復間隔
notification.repeatInterval = NSCalendarUnit.Calendar
// 設置提醒的文字內容
notification.alertBody = "本地推送";
//設置提醒彈出的alertView按鈕的文本
notification.alertAction = "我知道了"
if #available(iOS 8.2, *) {
notification.alertTitle = "notification alertTitle"
}
if #available(iOS 8.0, *) {
notification.category = "MyNotification" //這個很重要,跟上面的動作集合(UIMutableUserNotificationCategory)的identifier一樣
}
//這個很重要,跟上面的動作集合(UIMutableUserNotificationCategory)的identifier一樣
// 通知提示音 使用默認的
notification.soundName = UILocalNotificationDefaultSoundName
// 設置應用程序右上角的提醒個數
notification.applicationIconBadgeNumber = 1;
// 設定通知的userInfo,用來標識該通知
var userInfo:[NSObject : AnyObject] = [NSObject : AnyObject]()
userInfo["kLocalNotificationID"] = "LocalNotificationID"
userInfo["key"] = "Attention Please"
notification.userInfo = userInfo
// 將通知添加到系統中
application.presentLocalNotificationNow(notification)
//UIApplication.sharedApplication().scheduleLocalNotification(notification)
//UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
//當App從后臺即將回到前臺時觸發此事件
func applicationWillEnterForeground(application: UIApplication) {
print("\n\t applicationWillEnterForeground ")
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
//當App變成活動狀態時觸發此事件
func applicationDidBecomeActive(application: UIApplication) {
print("\n\t applicationDidBecomeActive ")
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
application.cancelAllLocalNotifications()
application.applicationIconBadgeNumber = 0
}
//當App退出時觸發此方法,一般用于保存某些特定的數據
func applicationWillTerminate(application: UIApplication) {
print("\n\t applicationWillTerminate ")
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
print("\n\t handleActionWithIdentifier forRemoteNotification \(identifier)")
completionHandler()
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
print("\n\t handleActionWithIdentifier forLocalNotification \(identifier)") //這里的identifier是按鈕的identifier
completionHandler() //最后一定要調用這上方法
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//這里應將device token發送到服務器端
print("\n\t didRegisterForRemoteNotificationsWithDeviceToken \(deviceToken.description)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("\n\t didFailToRegisterForRemoteNotificationsWithError \(error.code)")
}
// 注冊通知 alert 、 sound 、 badge ( 8.0 之后,必須要添加下面這段代碼,否則注冊失敗)
@available (iOS 8.0, *)
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print("\n\t didRegisterUserNotificationSettings \(notificationSettings)")
}
// 8.0 之前 收到遠程推送通知
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("\n\t didReceiveRemoteNotification \(userInfo)")
application.applicationIconBadgeNumber = 0
let notif = userInfo as NSDictionary
let apsDic = notif.objectForKey ( "aps" ) as! NSDictionary
let alertDic = apsDic.objectForKey ( "alert" ) as! String
let alertView = UIAlertView (title: " 系統本地通知 " , message: alertDic, delegate: nil , cancelButtonTitle: " 返回 " )
alertView.show ()
}
// 8.0 之后 收到遠程推送通知
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("\n\t didReceiveRemoteNotification fetchCompletionHandler \(userInfo)")
application.applicationIconBadgeNumber = 0
let notif = userInfo as NSDictionary
let apsDic = notif.objectForKey ( "aps" ) as! NSDictionary
let alertDic = apsDic.objectForKey ( "alert" ) as! String
let alertView = UIAlertView (title: " 遠程推送通知 " , message: alertDic, delegate: nil , cancelButtonTitle: " 返回 " )
alertView.show ()
}
// 收到本地通知
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("\n\t didReceiveLocalNotification \(notification)")
UIApplication.sharedApplication().cancelAllLocalNotifications()
let userInfo = notification.userInfo!
let title = userInfo["key"] as! String
let alert = UIAlertView()
alert.title = title
alert.message = notification.alertBody
alert.addButtonWithTitle(notification.alertAction!)
alert.cancelButtonIndex = 0
alert.show()
}
}