使用swift在后台播放歌曲的本地通知?

时间:2016-11-09 11:59:26

标签: ios swift avfoundation uilocalnotification

这是我的代码:

import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var audioPlayer:AVAudioPlayer?

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)

    let playAction = UIMutableUserNotificationAction()
    playAction.identifier = "PLAY"
    playAction.title = "play"
    playAction.activationMode = UIUserNotificationActivationMode.Background
    playAction.authenticationRequired = false
    playAction.destructive = true


    let playCategory = UIMutableUserNotificationCategory()
    playCategory.identifier = "PLAY_CATEGORY"
    playCategory.setActions([playAction],
                               forContext: UIUserNotificationActionContext.Default)

    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: NSSet(object: playCategory) as? Set<UIUserNotificationCategory>)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    return true
}
 func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if identifier == "PLAY" {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.playSound("play_tune")
       }
 func playSound(soundName: String)
{

    if (audioPlayer != nil && (audioPlayer?.playing)!) {
        return
    }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            print("AVAudioSession is Active")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

    let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    }catch {
        print("Error getting the audio file")
    }


}

一切都很好但是当我在通知中按播放时没有任何事情发生。我希望当用户收到通知时,如果他/她按下播放按钮,则应该在后台播放歌曲。

谢谢。

1 个答案:

答案 0 :(得分:0)

请在playSound功能中添加以下代码行

var soundID = SystemSoundID()
var soundFile = Bundle.main.path(forResource: "msg_tone", ofType: "mp3")!
AudioServicesCreateSystemSoundID((URL(fileURLWithPath: soundFile) as! CFURLRef), soundID)
AudioServicesPlaySystemSound(soundID)
变量coinSound之后

......