发布
社区首页 >问答首页 >带有自定义声音的UNMutableNotificationContent

带有自定义声音的UNMutableNotificationContent
EN

Stack Overflow用户
提问于 2019-01-05 16:39:16
回答 1查看 2.3K关注 0票数 3

我正在尝试创建一个简单的演示,在这里我点击一个按钮,然后出现一个自定义通知,并附带一个自定义声音。

发生的行为:

  • 通知在模拟器和连接设备(iPhone SE)上都正确显示。
  • 标准声音在模拟器上播放,而在设备上不播放。
  • 这个定制的声音根本不播放。在模拟器上,我得到默认的通知声音,而在设备上,我根本没有收到任何声音。

声音文件'alert.caf‘被添加到Assets.xcassets中。

这是我的类(在应用程序启动回调中处理了访问权限):

代码语言:javascript
代码运行次数:0
复制
import UIKit
import UserNotifications

class HomeViewController: UIViewController, UNUserNotificationCenterDelegate {

    @IBOutlet weak var btnNotification: UIButton!

    @IBAction func triggerNotification(_ sender: Any) {
        /* let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil) */
        execNotification()

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UNUserNotificationCenter.current().delegate = self

    }

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

    private func execNotification() {
        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = "UNUserNotification Sample"
        notificationContent.body = "Sample test msg"
        notificationContent.badge = 0
        notificationContent.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "alert.caf"))
        notificationContent.categoryIdentifier = "GENERAL"

        let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)
        let notificationRequest = UNNotificationRequest(identifier: "general", 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))")
            }
        }

    }

}

注意:我检查了所有可能导致警报不被播放的设置,但实际上没有任何理由。该应用程序的设置是正确的,没有“不要打扰”模式。

我使用Xcode 10.1

EN

回答 1

Stack Overflow用户

发布于 2019-01-05 17:16:20

请注意以下几点建议:

  • 确保声音文件位于当前可执行文件的主包中,或者位于当前应用程序容器目录(来源)的库/声音目录中。
  • 确保声音文件小于30秒。如果声音文件超过30秒,则系统将播放默认声音(来源)。
  • 确保在构建阶段将声音文件添加到目标的“复制捆绑资源”中。
  • 选择声音文件,并确保在其“目标成员资格”,您的应用程序的目标是正确选择。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54054002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档