【问题标题】:Play song in Notification在通知中播放歌曲
【发布时间】:2017-04-05 07:41:18
【问题描述】:

我想播放一首歌。当通知到来时。当应用程序处于前台模式时,我的代码工作正常。我想在应用程序处于后台模式时播放歌曲。请帮忙。

【问题讨论】:

    标签: swift push-notification swift3 apple-push-notifications


    【解决方案1】:

    为您的本地通知添加自定义声音

    Swift 3.0

     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        var state: UIApplicationState = application.applicationState
        if state == .active {
            var soundID: SystemSoundID
            var mainBundle: CFBundleRef = CFBundleGetMainBundle()
            var ref: CFURLRef? = CFBundleCopyResourceURL(mainBundle, ("mySoundName.wav" as? CFString), nil, nil)
            AudioServicesCreateSystemSoundID(ref, soundID)
            AudioServicesPlaySystemSound(soundID)
        }
        else {
            // Push Notification received in the background
        }
    }
    

    对于推送通知 将此添加到有效负载..

    {
     aps =
     {
        alert = "message";
        sound = "pushSound.caf";//this file will have to your bundle
       };
    }
    

    【讨论】:

    • 添加了3.0版本。
    【解决方案2】:

    您需要在 plist 文件中进行一些更改。

    1.) 将必需的后台模式设置为应用播放音频。

    2.) 将应用程序不在后台运行设置为是

    代码

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    var state: UIApplicationState = application.applicationState
    if state == .active {
        print("User Info : \(userInfo.description)")
        print("User Info Alert Message : \(userInfo["aps"]["alert"])")
        var messageString: String? = "\((userInfo["aps"] as? String)?["alert"] as? String)"
        var playSoundOnAlert: String? = "\((userInfo["aps"] as? String)?["sound"] as? String)"
        var url = URL(fileURLWithPath: "\(Bundle.main.resourcePath)/\(playSoundOnAlert)")
        var error: Error?
        audioPlayer = try? AVAudioPlayer(contentsOf: url)
        audioPlayer.numberOfLoops = 0
        audioPlayer.play()
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多