我正在尝试创建一个简单的演示,在这里我点击一个按钮,然后出现一个自定义通知,并附带一个自定义声音。
发生的行为:
声音文件'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
https://stackoverflow.com/questions/54054002
复制相似问题