UILocalNotification 总结

jopen 8年前

//

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

        

    }

    

}



来自: http://my.oschina.net/asjoker/blog/600128