显然,这在ios10中是可能的:

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

这个答案基本上说明了实现这一点所需的工具:

Displaying a stock iOS notification banner when your app is open and in the foreground?

我只是不太明白如何把它们放在一起.

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

我想展示徽章,doctor 提供

static var badge: UNNotificationPresentationOptions { get }

这里有点迷路.

然后我假设如果我想排除某个视图控制器获取这些徽章,并且我没有使用导航控制器,那么我发现这个代码会起作用:

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

}

为了在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 ?? "some unknown error")
        }     
        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])

    }

如果你想让你的通知横幅在整个应用程序中随处可见,那么你可以在AppDelegate中写入UNUserNotificationDelegate的委托,并将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]) 
    }
}

Check this link for more details
https://www.youtube.com/watch?v=Svul_gCtzck

Github Sample
https://github.com/kenechilearnscode/UserNotificationsTutorial

这是输出

enter image description here

enter image description here

Swift相关问答推荐

Swift UI在视图中排序不同的 struct

向文本元素添加背景色失败

无法创建MKAssociateRegion对象

UICollectionViewCompostionalLayout Collectionview单元格宽度在重新加载数据后未正确调整大小

在SwiftUI中,我如何确保带有符号的单词不会被拆分为两行?

如何增加 NSStatusBar 图像大小?

如何在应用程序区域永久更改 NSCursor?

使 tabview 垂直将视图移动到右侧 swift ui

我如何在 swift 中的 viewdidload 之前进行委托?

Swift:结果的失败类型不能是协议 - Type 'any ShadowError' cannot conform to Error

如何在一个视图控制器中创建具有相同行为的多个集合视图?

如何打印出此 struct 中的数据?

将基于MyProtocol的泛型函数的参数更改为使用存在的any MyProtocol或some MyProtocol是否会受到惩罚?

是否可以使任何协议符合 Codable?

使用自定义相机拍照 iOS 11.0 Swift 4. 更新错误

如何快速制作虚线?

为什么 swift 中的类没有存储类型属性?

如何使用 swift 将 Images.xcassets 中的图像加载到 UIImage 中

Swift if 语句 - 多个条件用逗号分隔?

如何使用 swift 在 tableview 中填充两个不同数组的两个部分?