【问题标题】: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

}

【问题讨论】:

    标签: ios swift localnotification swift5


    【解决方案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)
    }
    

    【讨论】:

    • 应用在后台时会播放吗?
    • 是的,它会播放,用你的文件名替换声音名称。
    • 检查用默认声音替换声音然后看看它是否工作
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2021-10-11
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多