I am using AVPlayer to play audio from an URL. Everything works as expected until the APP goes on background or the iphone enter in sleep mode.
How can I prevent this from happening.
I've added to the info.plist:
Here is my code.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let playTrackID = tracks[indexPath.row].trackID
let urlString = url
let url = NSURL(string: urlString)!
avPlayer = AVPlayer(URL:url)
avPlayer.play()
}
Any idea?
UPDATE: SOLVED by @Danil Gontovnik
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let playTrackID = tracks[indexPath.row].trackID
let urlString = url
let url = NSURL(string: urlString)!
do {
avPlayer = AVPlayer(URL:url)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down")
}
avPlayer.play()
I think that you forgot to set your AVAudioSession to be active. Try to add this code:
var categoryError: NSError?
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError)
if categoryError != nil {
// Handle error
}
var activeError: NSError?;
AVAudioSession.sharedInstance().setActive(true, error: &activeError)
if activeError != nil {
// Handle error
}
More information on AVAudioSession can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With