【发布时间】:2021-10-11 13:08:09
【问题描述】:
我正在制作一个闹钟应用程序,并且我已确认我的闹钟通知被正确触发,但声音并不总是按我预期的那样播放。
例如,当手机不处于静音模式时,通知会成功播放声音(好的,太好了!)。但是,当手机处于静音模式时,声音不会播放,即使应用程序仍在后台运行(不太好......)。
我知道静音模式应该使所有通知声音静音,但我已经从 App Store 下载了其他闹钟应用程序(如 Alarmy),即使手机也能以某种方式播放通知声音只要应用程序仍在后台运行,就处于静音模式。只有当应用程序完全退出时,静音模式才会生效。
有谁知道如何实现这个结果?我需要在我的代码或 plist 文件中声明一些设置或选项吗?我已经搜索了互联网,但没有找到任何关于这个特定问题的信息......
我设置 AVAudioSession 类别的代码:
private func setAudioCategory() {
do {
// Enable sound (even while in silent mode) as long as app is in foreground.
try AVAudioSession.sharedInstance().setCategory(.playback)
}
catch {
print(error.localizedDescription)
}
}
我设置通知的代码:
/// Sets a local user notification for the provided `Alarm` object.
static func set(_ alarm: Alarm) {
// Configure the notification's content.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: K.Keys.notificationTitle, arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: K.Keys.notificationBody, arguments: nil)
// Get sound name
let soundName: String = UserDefaultsManager.getAlarmSound().fileNameFull
// Set sound
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: soundName))
content.categoryIdentifier = "Alarm"
// Configure the time the notification should occur.
var date = DateComponents()
date.hour = alarm.hour
date.minute = alarm.minute
// Create the trigger & request
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
let request = UNNotificationRequest(identifier: alarm.notifID, content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: { error in
if error != nil {
// TODO: Show Alert for Error
return
}
})
}
【问题讨论】:
-
事实上,您冒着被 Apple 在审核期间拒绝您的应用程序的风险,因为框架不允许您的应用程序在静音模式下运行声音。但如果你仍然想冒险,看看这个:andrewmarinov.com/building-an-alarm-app-on-ios
-
不幸的是,将音频会话设置为
.playAndRecord并在 .plist 文件中为Required Background Modes启用音频似乎不起作用...(来自链接文章中的“麦克风方法”)。 -
声音文件长度不能超过30秒。
-
@Ramis 指出。该文件在不处于静音模式时已经正确播放,所以这不是问题。
-
@Climbatize 感谢您的贡献。如果您好奇我是如何解决的,请查看下面的答案。
标签: ios swift nsnotificationcenter avaudiosession usernotifications