-1

I am making a music player app for my school project.

I keep getting an error that says fatal error: unexpectedly found nil while unwrapping an Optional value.

Please help me with a detailed explanation so I can fix my app.

This is all of the code: the error is bolded

============================================

import UIKit
import AVFoundation

var songs:[String] = []
var audioPlayer = AVAudioPlayer()

class FirstViewController: UIViewController, UITableViewDelegate,       UITableViewDataSource {

@IBOutlet weak var myTabelView: UITableView!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return songs.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    cell.textLabel?.text = songs[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    do
    {
        let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3") //17:53
        **try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL) //18:57 

    }
    catch
    {
            print("ERROR")
    }
}



override func viewDidLoad() {
    super.viewDidLoad()
    gettingSongName()
}

func gettingSongName()  // Get the names of all the songs
{
     let folderUrl = URL(fileURLWithPath: Bundle.main.resourcePath!)

    do
    {
        let songPath = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) // Axcess all of the song files

        for song in songPath
        {
            var mySong = song.absoluteString


            if mySong.contains(".mp3")
            {
                let findString = mySong.components(separatedBy: "/")
                mySong = (findString[findString.count-1])
                mySong = mySong.replacingOccurrences(of: "%20", with: " ")
                mySong = mySong.replacingOccurrences(of: ".mp3", with: " ")
                songs.append(mySong)

            }
        }

        myTabelView.reloadData()
    }
    catch
    {

    }

}


}
Harshal Valanda
  • 5,331
  • 26
  • 63

1 Answers1

0

Bundle.main.path(forResource:) method returns an optional value. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all. So if you try to unwrap an optional when there is no value using ! symbol you will get the fatal error: unexpectedly found nil while unwrapping an Optional value error. To handle optionals use optional binding i.e. if let value = optional syntax so if there is an value then it will make it available or ignore if the value is nil.

do
{
   if let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3") {
      try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath))
   }
} catch {
     print(error.localizedDescription)
}
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60