2017-06-03 10 views
-1

私の学校のプロジェクト用の音楽プレーヤーアプリを作っています。エラー:「致命的なエラー:音楽プレーヤーのアプリケーションのオプション値をアンラッピングしている間に予期せぬエラーが発生しました」

私は私のアプリを修正することができるようにfatal error: unexpectedly found nil while unwrapping an Optional value.

は、詳細な説明で私を助けてくださいというエラーを取得しておきます。

これは、すべてのコードです:エラーが

を太字にされ=============================== =============

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 
    { 

    } 

} 


} 

答えて

0

Bundle.main.path(forResource:) method returns an optional valueoptionalは、2つの可能性を表します。値があり、その値にアクセスするためにオプションのラップを解除するか、まったく値がありません。したがって、!シンボルを使用して値がない場合にオプションのラップを解こうとすると、fatal error: unexpectedly found nil while unwrapping an Optional valueエラーが発生します。 optionalsを処理するには、オプションのバインディング、つまりif let value = optionalの構文を使用します。値がある場合、その値を使用可能にするか、値が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) 
} 
+0

これでエラーは発生しません。ただ、唯一の問題は、曲をクリックすると再生されないことです。助けてください。 –

関連する問題