【发布时间】:2019-01-05 16:39:16
【问题描述】:
我正在尝试创建一个简单的演示,在该演示中单击一个按钮,会出现一个自定义通知,并伴有自定义声音。
发生的行为:
- 通知在模拟器和连接的设备 (iPhone SE) 上都能正常显示
- 标准声音在模拟器上播放,但在设备上不播放。
- 自定义声音根本不播放。在模拟器上我得到默认的通知声音,而在设备上我根本没有任何声音。
声音文件“alert.caf”已添加到 Assets.xcassets。
这是我的班级(访问权限已在应用启动回调中处理):
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
【问题讨论】: