问题描述:

I'm getting an error in the line of var filePathUrl. The error code is "Value of optional type 'String?' not unwrapped: did you mean to use '!' or '?'?'". How can I fix this error?

import UIKit

import AVFoundation

class PlayMusicViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view.

var daten = NSBundle.mainBundle().pathForResource("Kool_Savas_Auge", ofType: "mp3")

var filePathUrl = NSURL.fileURLWithPath(daten)

var audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, fileTypeHint: nil)

}

@IBAction func PlayMusic(sender: UIButton) {

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

/*

// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

// Get the new view controller using segue.destinationViewController.

// Pass the selected object to the new view controller.

}

*/

}

网友答案:

try with

var filePathUrl = NSURL.fileURLWithPath(daten!)

Could you please tell me what I did wrong?

an exclamation mark (!) after an optional value to force the unwrapping of its value . please check this one Swift 2: !, ? -" Value of optional type "..." not unwrapped"

UPDATE :

for example :

var daten = NSBundle.mainBundle().pathForResource("Kool_Savas_Auge", ofType: "mp3")

    var filePathUrl = NSURL.fileURLWithPath(daten!)

    do{
        var audioPlayer = try AVAudioPlayer(contentsOfURL: filePathUrl, fileTypeHint: nil)

        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    catch let err as NSError{
        print(err.debugDescription);
    }
相关阅读:
Top