当应用程序处于前台时显示本地通知Swift 3

显然这是现在可以与ios10:

optional func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) 

这个答案基本上说,需要做的工具:

当应用程序打开并在前台显示股票iOS通知横幅?

我只是不太了解如何把它放在一起。

我不知道这是多么重要,但我不能保持可选的function和Xcode要我切换到私人。

我试图展示徽章和文档提供

 static var badge: UNNotificationPresentationOptions { get } 

有一点在这里丢失

然后我假设,如果我想排除某些视图控制器获得这些徽章,我不使用导航控制器,我发现这个代码将工作? :var window:UIWindow?

 if let viewControllers = window?.rootViewController?.childViewControllers { for viewController in viewControllers { if viewController.isKindOfClass(MyViewControllerClass) { print("Found it!!!") } } } 

在iOS 10中打开应用程序时,有一个委托方法来显示通知。您必须实现此目的才能在应用程序打开时获取丰富的通知。

 extension ViewController:UNUserNotificationCenterDelegate { //for displaying notification when app is in foreground func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //If you don't want to show notification when app is open, do something here else and make a return here. //Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. ie completionHandler. completionHandler([.alert,.badge]) } // For handling tap and user actions func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case "action1": print("Action First Tapped") case "action2": print("Action Second Tapped") default: break } completionHandler() } } 

为了在iOS 10中安排通知并提供徽章

 override func viewDidLoad() { super.viewDidLoad() // set UNUserNotificationCenter delegate to self UNUserNotificationCenter.current().delegate = self scheduleNotifications() } func scheduleNotifications() { let content = UNMutableNotificationContent() let requestIdentifier = "rajanNotification" content.badge = 1 content.title = "This is a rich notification" content.subtitle = "Hello there, I am Rajan Maheshwari" content.body = "Hello body" content.categoryIdentifier = "actionCategory" content.sound = UNNotificationSound.default() // If you want to attach any image to show in local notification let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg") do { let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil) content.attachments = [attachment!] } let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3.0, repeats: false) let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error:Error?) in if error != nil { print(error?.localizedDescription) } print("Notification Register Success") } } 

为了在AppDelegate中注册,我们必须在didFinishLaunchingWithOptions编写这段代码

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. registerForRichNotifications() return true } 

我在这里也定义了一些行为。 你可以跳过它们

 func registerForRichNotifications() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted:Bool, error:Error?) in if error != nil { print(error?.localizedDescription) } if granted { print("Permission granted") } else { print("Permission not granted") } } //actions defination let action1 = UNNotificationAction(identifier: "action1", title: "Action First", options: [.foreground]) let action2 = UNNotificationAction(identifier: "action2", title: "Action Second", options: [.foreground]) let category = UNNotificationCategory(identifier: "actionCategory", actions: [action1,action2], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([category]) } 

检查此链接了解更多详情
https://www.youtube.com/watch?v=Svul_gCtzck

Github示例
https://github.com/kenechilearnscode/UserNotificationsTutorial

这是输出

在这里输入图像描述

在这里输入图像描述

让您的通知在您的应用处于前台时显示的关键还在于:

 content.setValue(true, forKey: "shouldAlwaysAlertWhileAppIsForeground") 

在您的UNNotificationRequest 。 至于其余的,请看Rajan Maheshwari的优秀答案。

Swift 3 | iOS 10+

假设您知道如何安排本地通知:

 func scheduleLocalNotification(forDate notificationDate: Date) { let calendar = Calendar.init(identifier: .gregorian) let requestId: String = "123" let title: String = "Notification Title" let body: String = "Notification Body" // construct notification content let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil) content.sound = UNNotificationSound.default() content.badge = 1 content.userInfo = [ "key1": "value1" ] // configure trigger let calendarComponents: [Calendar.Component] = [.year, .month, .day, .hour, .minute] let dateComponents = calendar.dateComponents(calendarComponents, from: notificationDate) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) // create the request let request = UNNotificationRequest.init(identifier: requestId, content: content, trigger: trigger) // schedule notification UNUserNotificationCenter.current().add(request) { (error: Error?) in if let error = error { // handle error } } } 

您需要使您的AppDelegate实现UNUserNotificationCenterDelegate协议,并将其设置为UNUserNotificationCenter.current().delegate = self的通知中心的委托。

 // AppDelegate.swift import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // set app delegate as notification center delegate UNUserNotificationCenter.current().delegate = self } } extension AppDelegate: UNUserNotificationCenterDelegate { // called when user interacts with notification (app not running in foreground) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // do something with the notification print(response.notification.request.content.userInfo) // the docs say you should execute this asap return completionHandler() } // called if app is running in foreground func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // show alert while app is running in foreground return completionHandler(UNNotificationPresentationOptions.alert) } } 

现在,当您的应用处于前台时,您的本地通知将会显示。

请参阅UNUserNotificationCenterDelegate文档以供参考。