2016-11-09 1 views
0

Вот мой код:Местное уведомление для воспроизведения песни в фоновом режиме с помощью swift?

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") 
    } 


} 

Все работает нормально, но когда я нажимаю играть в уведомлении ничего не происходит. Я хочу, чтобы пользователь получал уведомление, и если он нажимает кнопку воспроизведения, песня должна воспроизводиться в фоновом режиме.

спасибо.

ответ

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 ...

Смежные вопросы