苹果推送主要分为服务器的推送和本地的推送 服务器的推送主要是要注册ID 所以暂不说 先把本地的推送代码附上
逻辑图如下
本地推送是NSLocalNotification实现的
通过在AppDelegate.swift中添加代码,主要在其中添加添加推送服务
App第一次执行时被执行过一次,每次App从后台激活时都不执行该方法
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
func applicationWillResignActive(application: UIApplication) {
func applicationDidEnterBackground(application: UIApplication) {应用程序从后台回到前台 执行该方法
func applicationWillEnterForeground(application: UIApplication) {
func applicationDidBecomeActive(application: UIApplication) {应用程序将要推出,通常是用来保存数据和一些推出前的清理工作
func applicationWillTerminate(application: UIApplication) {注册本地账号 收到推送得到用户的许可 在didFinishLaunchingWithOptions中添加代码
let ver = UIDevice.currentDevice().systemVersion if (ver as NSString).floatValue >= 8.0 { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound , categories:nil )) }
在 applicationDidEnterBackground中添加代码
//清除所有的本地推送 UIApplication.sharedApplication().cancelAllLocalNotifications() //初始化本地通知对象 let notification = UILocalNotification() //设置通知的提醒时间 var currentDate = NSDate() notification.fireDate = currentDate.dateByAddingTimeInterval(5.0) //设置推送使用本地时区 notification.timeZone = NSTimeZone.defaultTimeZone() //设置重复的间隔 notification.repeatInterval = NSCalendarUnit.Calendar //设置提醒的文字内容 notification.alertBody = "5秒本地推送" //设置提醒的文字内容 notification.alertAction = "我知道了" //通知提示音使用默认的 notification.soundName = UILocalNotificationDefaultSoundName //设置应用程序右上角的提醒个数 notification.applicationIconBadgeNumber = 1 //设置通知的userInfo,用来标示该通知 var aUserInfo = NSMutableDictionary() aUserInfo["KLocalNotificationID"] = "LocalNotificationID" notification.userInfo = aUserInfo as [NSObject : AnyObject] //将通知添加到系统当中 UIApplication.sharedApplication().scheduleLocalNotification(notification) }
收到推送 如果点击 会重新进入App 此时调佣 didReceiveLocalNotification方法
//收到本地推送的通知 func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { //设置badge的数目 UIApplication.sharedApplication().applicationIconBadgeNumber = 0 let alert = UIAlertController(title: "通知", message: "这是一个推送\(notification.alertBody)", preferredStyle: UIAlertControllerStyle.Alert) alert.showViewController(alert, sender: nil) }
//当应用程序重新进入活动状态时调用该方法 func applicationDidBecomeActive(application: UIApplication) { // 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. //清除本地所用推送 UIApplication.sharedApplication().cancelAllLocalNotifications() //初始化本地的通知对象 let notification = UILocalNotification() //设置应用程序右上角的提醒个数 notification.applicationIconBadgeNumber = 0 }