ios - 收到本地通知时无法播放音乐,当应用程序快速处于后台状态时

标签 ios swift localnotification swift5

我正在安排一个本地通知作为应用程序的闹钟,我在其中设置收到本地通知时的音乐和振动。当应用程序处于前台状态时,一切正常,播放音乐,振动。

但是当应用程序处于后台状态时,只有默认的通知音乐,即只有一次,不会重复,并且会发生单一振动。

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

}

最佳答案

在 AppDelegate.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)
}

关于ios - 收到本地通知时无法播放音乐,当应用程序快速处于后台状态时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58370253/

相关文章:

ios - spritekit SKAction.resizeToHeight 不重复

iOS - 阴影在 UILabel 上传播

ios - 向 Firebase 中的其他用户发送预先编写的应用内用户通知

ios - 计算待处理的本地通知

ios - 使用 Facebook sdk 与 UIImage 分享图表故事

ios - 发出多个异步请求,但仅等待一个

android - 错误:找不到执行代理::LocalNotification::deviceready

ios - 避免 swift 覆盖本地通知

ios - 创建新单元格后执行某些操作

web-services - 如何使用 NSURLSession 在 Swift 中定义内容类型