Swift - 本地通知不会被触发 [英] Swift - Local Notification doesn't get triggered

查看:59
本文介绍了Swift - 本地通知不会被触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Swift 3 中编码,我只是尝试现在发送通知,没有任何延迟或间隔.然而,通知永远不会被触发.这是我的代码..

I am coding in Swift 3 and I am simply trying to send a notification now without any delays or intervals. However the notification never gets triggered. Here's my code..

ViewController 代码

import UserNotifications

class HomeViewController: UIViewController{
    var isGrantedNotificationAccess:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert,.sound,.badge],
            completionHandler: { (granted,error) in
                self.isGrantedNotificationAccess = granted
        })

        if isGrantedNotificationAccess{
            triggerNotification()
        }
    }

    //triggerNotification func goes here
}

triggerNotification 函数:

func triggerNotification(){
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Notification Testing", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "This is a test", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber;
    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 1.0,
        repeats: false)

    let request = UNNotificationRequest.init(identifier: "testTriggerNotif", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)
}

我做错了什么?

推荐答案

您忽略了处理,当应用程序处于前台时,您没有指定通知的外观或呈现方式.

在添加通知时设置下面的行以指定您要在用户使用应用时显示横幅(iOS 10 新功能).

Set below line while adding notification to specify that you want to show banner while user is using app (iOS 10 new feature).

在构建您的 UNMutableNotificationContent 对象时添加以下代码行:

Add the following line of code when constructing your UNMutableNotificationContent object:

content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")

您还应该在 AppDelegate 中添加以下方法:

You should also add the following method in your AppDelegate:

// This method will be called when app received push notifications in foreground

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

这篇关于Swift - 本地通知不会被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆