Repaz Kung Repaz Kung - 2 years ago 108
Objective-C Question

Fixing error AudioPlayer

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() {

// 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() {
// 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.


Answer Source

try with

var filePathUrl = NSURL.fileURLWithPath(daten!)

Could you please tell me what I did wrong?

enter image description here

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"


for example :

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

    var filePathUrl = NSURL.fileURLWithPath(daten!)

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

    catch let err as NSError{
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download