Search code examples
iosaudiouiviewcontrollerxcode11swift5

Sound stops when navigating through ViewControllers


I am currently trying to make an app in Xcode that acts as a music app. It currently have 2 ViewControllers and it look like this. ViewControllers Code for MusicViewController:

import UIKit
import AVFoundation

class MusicViewController: UITableViewController, UINavigationControllerDelegate {

    let songs = ["Sugar", "Da-i Foale", "Kush"]
    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.isHidden = false
    }

    //MARK: - Data Delegate Methods
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return songs.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath)

        cell.textLabel?.text = songs[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        let path = Bundle.main.path(forResource: songs[indexPath.row], ofType: "mp3")!
        let url = URL(fileURLWithPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            try AVAudioSession.sharedInstance().setCategory(.playback)
            player.play()
        } catch {
            print(error)
        }
    }
}

The idea was to navigate through other ViewControllers without the music to stop, but it doesn't work. I have to say that at the moment I don't use prepareForSegue() or other similar methods. This is because ViewController gets destroyed after you dismiss it through the back button from navigation bar? Thank you for your attention, waiting for your answers.


Solution

  • Probably your player instances deallocated when ViewController goes into background.

    You should put AVAudioPlayer instance to AppDelegate.