Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow users background music in swift 2.0

I am looking for some code to allow the user to play music from their phone while still using my app. Previously before swift 2.0 i would put this in the app delegate and it would work perfectly:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

Does anyone know how to implement this in swift 2.0?

like image 999
Lucas Azzopardi Avatar asked Sep 19 '15 22:09

Lucas Azzopardi


1 Answers

The following would be the syntax for Swift 2 calling setCategory and setActive on AVSession:

do
{
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError
{
    print(error)
}

OR

do
{
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError
{
    print(error)
}
like image 155
Unheilig Avatar answered Oct 22 '22 08:10

Unheilig