我正在制作一个闹钟应用程序,我确认我的闹钟通知被正确触发了,但是声音并不总是按照我预期的播放。
例如,当手机没有静音时,通知会成功地播放声音(好的!)。然而,当手机处于静音模式时,即使应用程序仍在后台运行,声音也不会播放(不太好)。
我知道静音模式应该消除所有通知声音,但我从App Store下载了其他闹钟应用程序(如Alarmy),它们以某种方式能够使其通知声音播放,即使手机处于静音模式下,只要应用程序仍在后台运行。只有在完全退出应用程序时,静音模式才会生效。
是否有人知道如何实现这个结果?是否有一些设置或选项,需要在我的代码或plist文件中声明?我搜遍了互联网,但没有找到针对这个特定问题的任何东西...
设置AVAudioSession类别的我的代码:
例如,当手机没有静音时,通知会成功地播放声音(好的!)。然而,当手机处于静音模式时,即使应用程序仍在后台运行,声音也不会播放(不太好)。
我知道静音模式应该消除所有通知声音,但我从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
}
})
}
.playAndRecord
并在Required Background Modes
的.plist文件中启用音频似乎不起作用...(来自链接文章中的“麦克风方法”)。 - Eric