当我的应用程序处于静音模式和终止状态时,我需要在我的 iOS 应用程序中接收推送通知时播放声音。 下面的代码不起作用,返回错误操作无法完成。 (OSStatus 错误 561015905。)
NotificationService.swift
导入用户通知
导入 AVFoundation
导入媒体播放器
类 NotificationService:UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
var audioPlayer = AVAudioPlayer()
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
playSound()
if let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
扩展通知服务{
//MARK: - Set up
private func playSound() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
if let url = URL(string: "file:///private/var/mobile/Containers/Shared/AppGroup/9A4FCED-7432FE-FEW-A559-234FBW/Library/Sounds/Update.caf") {
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.caf.rawValue)
audioPlayer.volume = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { // Give 5 sec delay to play audio or else audio will not hearable
self.audioPlayer.play()
}
}
} catch {
print("[SoundPlayer] There was an error \(error.localizedDescription):")
}
if (audioPlayer.isPlaying) {
audioPlayer.stop()
}
audioPlayer.play()
}
}