ios - Swift - 本地通知不会被触发

标签 ios swift xcode notifications uilocalnotification

我正在使用 Swift 3 进行编码,我只是想立即发送通知,没有任何延迟或间隔。但是,通知永远不会被触发。这是我的代码..

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
}

触发通知函数:

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 新功能)。

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

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

您还应该在 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)        
}

关于ios - Swift - 本地通知不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373321/

相关文章:

ios - 如果观察者已在 Swift 中注册,如何获取

ios - BFTask 的值类型没有成员生成器 : Swift 2. 0

ios - 如何快速重新启动计时器

swift - 如何在附加到 UITextField 的 UIPickerView 上设置 selectRow

ios - 为所有设备调整 iOS App Preview 的大小

iphone - 如何使 UINavigationBar 不下推 View ?

swift - 如何将默认 bool 值作为 true 或 false 保存到 coreData?

android - phonegap 构建应用程序的 Manifest.xml 和 config.xml 之间的区别

iphone - 当触摸移动时找到我们触摸下的物体

ios - 使用转换(_ :to:) method in swift