当应用程序在前景Swift 3时获取本地通知

use*_*041 35 ios uilocalnotification swift swift3 unusernotificationcenter

显然,ios10现在可以实现这一点:

optional func userNotificationCenter(_ center: UNUserNotificationCenter, 
                 willPresent notification: UNNotification, 
  withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
Run Code Online (Sandbox Code Playgroud)

这个答案基本上说明了做这件事所需的工具:

当您的应用程序处于打开状态且位于前台时显示库存iOS通知横幅?

我只是不太了解如何将它们放在一起.

我不知道这有多重要,但我无法保留可选的func,xcode要我将其切换为私有.

我正试图展示徽章,文档提供

static var badge: UNNotificationPresentationOptions { get }
Run Code Online (Sandbox Code Playgroud)

这里很少丢失.

然后我假设我想要排除某个视图控制器获取这些徽章并且我没有使用导航控制器这个代码我发现它会起作用吗?:var窗口:UIWindow?

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

Raj*_*ari 79

在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. i.e. completionHandler.

        completionHandler([.alert, .badge, .sound]) 
    }

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

}
Run Code Online (Sandbox Code Playgroud)

为了在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")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我也在这里定义了行动.你可以跳过它们

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])

    }
Run Code Online (Sandbox Code Playgroud)

如果您希望您的通知横幅应该显示在整个应用程序的任何位置,那么您可以编写UNUserNotificationDelegatein 的委托AppDelegate并使UNUserNotificationCenter当前委托AppDelegate

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(response.notification.request.content.userInfo)
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound]) 
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请访问此链接
https://www.youtube.com/watch?v=Svul_gCtzck

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

这是输出

在此输入图像描述

在此输入图像描述


Der*_*ike 16

斯威夫特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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要使您的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)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您的应用位于前台时,您的本地通知就会显示.

请参阅UNUserNotificationCenterDelegate文档以供参考.


小智 14

在应用程序位于前台时显示通知的关键还包括:

content.setValue(true, forKey: "shouldAlwaysAlertWhileAppIsForeground")
Run Code Online (Sandbox Code Playgroud)

在你的UNNotificationRequest.至于其他方面,请参阅Rajan Maheshwari的优秀答案.

  • 这些内容不再有效 - 应用程序因错误而崩溃 - SetValueForUndefineKey:“shouldAlwaysAlertWhileAppIsForeground” (3认同)
  • 如果您的“UNUserNotificationCenterDelegate”委托和操作类别的注册设置正确,则不必设置此项。委托中的第一个方法是处理这个应用程序在前台的情况。设置此值是无证的,可能会违反应用商店指南。 (2认同)

Sou*_*har 6

当您的应用在前台打开时 userNotificationCenter 方法调用

func userNotificationCenter(_ center: UNUserNotificationCenter,
   willPresent notification: UNNotification, 
   withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler(.alert)
}
Run Code Online (Sandbox Code Playgroud)