收到本地通知时无法播放音乐,当应用程序处于后台状态时
Posted
技术标签:
【中文标题】收到本地通知时无法播放音乐,当应用程序处于后台状态时【英文标题】:Not able to play the music when recived LocalNotification, when app is in background state in swift 【发布时间】:2019-10-14 04:49:56 【问题描述】:我正在安排一个本地通知作为应用程序的警报,我正在设置收到本地通知时的音乐和振动。当应用程序处于前台状态时,一切正常,播放音乐,振动。
但是当应用程序处于后台状态时,只会出现默认通知音乐,即仅一次不重复且会发生单次振动。
func application(_ application: UIApplication, didReceive notification: UILocalNotification)
//show an alert window
var isSnooze: Bool = false
var soundName: String = ""
var index: Int = -1
if let userInfo = notification.userInfo
isSnooze = userInfo["snooze"] as! Bool
soundName = userInfo["soundName"] as! String
index = userInfo["index"] as! Int
playSound(soundName)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
mainVC?.notification = notification
mainVC?.isFromNotificationDelegate = true
let nav = UINavigationController(rootViewController: mainVC!)
self.window?.rootViewController = nav
【问题讨论】:
【参考方案1】:在 AppDellegate.swift 中注册通知
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil))
return true
现在,使用以下功能安排您的通知,它会在收到通知时自动播放您的自定义声音
func localnotification (firedate:NSDate)
var localNotification:UILocalNotification = UILocalNotification()
localNotification.fireDate = firedate
localNotification.alertBody = "time to woke up"
localNotification.soundName = "alarm.wav"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
【讨论】:
应用在后台时会播放吗? 是的,它会播放,用你的文件名替换声音名称。 检查用默认声音替换声音然后看看它是否工作以上是关于收到本地通知时无法播放音乐,当应用程序处于后台状态时的主要内容,如果未能解决你的问题,请参考以下文章