使用未声明的类型'UNUserNotificationCenter'

Sha*_*ram 11 ios swift unusernotificationcenter

我想在应用程序处于前台时显示推送通知的横幅.我实现这个方法来显示通知:

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

但是这个错误收到了未申报类型'UNUserNotificationCenter'的使用 在此输入图像描述

Ahm*_*d F 22

您所要做的就是导入UserNotifications框架:

import UserNotifications
Run Code Online (Sandbox Code Playgroud)

另外,请确保符合UNUserNotificationCenterDelegate.作为一种好的做法,我建议通过以下方式实现它extension:

如果你不熟悉代表团,你可能要检查这个了.

import UIKit
// add this:
import UserNotifications

class ViewController: UIViewController {
    .
    .
    .

    // somewhere in your code:
    UNUserNotificationCenter.current().delegate = delegateObject
}

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