【问题标题】:Swift UNUserNotification does not trigger soundSwift UNUserNotification 不会触发声音
【发布时间】:2017-07-08 04:14:34
【问题描述】:

这是我的UNUserNotification代码

     func scheduleNotification() {
        UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
        switch notificationSettings.authorizationStatus {
        case .notDetermined:
            self.requestAuthorization(completionHandler: { (success) in
                guard success else { return }

                // Schedule Local Notification
                self.scheduleLocalNotification()
            })

        case .authorized:
            // Schedule Local Notification
            self.scheduleLocalNotification()


        case .denied:
            print("Application Not Allowed to Display Notifications")
        }
      }
   }

    private func scheduleLocalNotification() {
        // Create Notification Content
        let notificationContent = UNMutableNotificationContent()

        // Configure Notification Content
        notificationContent.title = "Hello"
        notificationContent.body = ""

        // Add Trigger
        let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)

        // Create Notification Request
        let notificationRequest = UNNotificationRequest(identifier: id, content: notificationContent, trigger: notificationTrigger)

        // Add Request to User Notification Center
        UNUserNotificationCenter.current().add(notificationRequest) { (error) in
            if let error = error {
                print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
            }
        }
    }

    private func requestAuthorization(completionHandler: @escaping (_ success: Bool) -> ()) {
        // Request Authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
            if let error = error {
                print("Request Authorization Failed (\(error), \(error.localizedDescription))")
            }

            completionHandler(success)
        }
    }

它在通话后 10 秒安排通知,它可以工作,通知显示在锁定屏幕上,问题是它不会触发任何声音/振动。
根据要求,我正在设置这些选项[.alert, .sound, .badge],我错过了什么?
p.s.我愿意设置自定义声音,默认的就够了

【问题讨论】:

    标签: ios swift unnotificationrequest unnotificationtrigger


    【解决方案1】:

    您缺少播放声音的关键元素:

    notificationContent.sound = UNNotificationSound.default() 
    

    包含UNMutableNotificationContent 应该可以解决您的问题。

    【讨论】:

    • 是的,这是缺少的行,谢谢。尽管在我看来有点奇怪,考虑到我在选项中请求.sound 的事实,我必须明确设置默认值:)
    • 不客气!我同意;通知的一般工作方式有点笨拙——远程通知非常如此。
    • 即使在设置了这个默认声音之后,它对我也不起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2015-09-30
    相关资源
    最近更新 更多