Swift - 本地通知不会被触发

Din*_*uka 2 xcode notifications ios 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
}
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Muh*_*nan 7

您错过了处理,当应用程序处于前台时,您没有指定通知的外观或显示方式

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

content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
Run Code Online (Sandbox Code Playgroud)

//更新的triggerNotification

// 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)        
}
Run Code Online (Sandbox Code Playgroud)

在AppDelegate中添加以下方法

content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
Run Code Online (Sandbox Code Playgroud)

  • iOS 12中不再支持`shouldAlwaysAlertWhileAppIsForeground`,代码崩溃. (11认同)
  • 比尔提到的@theReverend,实现了'willPresent`委托就是所需要的. (3认同)
  • setValue(forKey :)方法是一个完全没有文档的密钥,不能保证将来(或根本没有)工作.它也没有必要.UNUserNotificationCenter委托方法就是您所需要的,并且已记录在案.你必须在app委托中专门实现`UNUserNotificationCenterDelegate`,并将`UNUserNotificationCenter`的委托设置为`didFinishLaunchingWithOptions`中的app委托以使其工作. (2认同)