// 执行通知一定要退出应用或挂起应用(进入后台)才能收到通知。
1、在iOS8及其以后版本中使用本地消息需要先获得用户的许可,否则无法成功注册本地消息。因此,我们将询问用户许可的代码片段添加到了app启动后的入口方法中(AppDelegate
中的didFinishLaunchingWithOptions
)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { var version=UIDevice.currentDevice().systemVersion if (version as NSString).floatValue>=8.0{ application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil)) } self.window=UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor=UIColor.whiteColor() self.window!.makeKeyAndVisible() self.window!.rootViewController=TB_Home() return true }
2、发送通知
func sendLocalNotification(){ //创建本地通知 var notification=UILocalNotification() //通知触发时间(10秒后触发) notification.fireDate=NSDate(timeIntervalSinceNow: 10) //通知时区(使用本地时区) notification.timeZone=NSTimeZone.defaultTimeZone() //通知提示标题 notification.alertTitle="messageTitle" //通知提示内容 notification.alertBody="messageBody" //通知提示音(使用默认的通知提示音) notification.soundName=UILocalNotificationDefaultSoundName //应用程序右上角显示的数字+1 notification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber+1 //启动这个通知 UIApplication.sharedApplication().scheduleLocalNotification(notification) }
3、进入前台,清除右上角图标及当前应用所有通知
func applicationWillEnterForeground(application: UIApplication) { application.applicationIconBadgeNumber=0 //程序右上角图标设置0 application.cancelAllLocalNotifications() //清除当前应用所有通知 }
时间: 2024-10-07 10:50:45