fatal error: unexpectedly found nil while unwrapping - swift

why I am getting Thread 1:EXE_BAD_INSTRUCTION
this is my code
override func viewDidAppear(animated: Bool) {
var fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")!)
var error: NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: fileclocaiton as String), error: &error)
}

var fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")!)
This line is the source of crash. Are you sure that you have the same resource as your navigationItem.title is ? Is navigationItem.title same as title property on UIViewController ? That you have to try out and make sure that the resource of that type exist. You could avoid crash in case the resource is not found using if let as,
if let fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")) {
... do rest of your coding here.
}

Related

Why do I keep getting this error??? fatal error: unexpectedly found nil while unwrapping an Optional value

I am trying to create an app with sound built in. Whenever I try to build my program I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is my code:
var magicSound: AVAudioPlayer = AVAudioPlayer()
#IBOutlet var Answer: UILabel!
var AnswerArray = ["Yes", "No", "Maybe", "Try Again", "Not Now", "No Doubt", "Yes Indeed", "Of course", "Definetley Not"]
var chosenAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: ".wav")
do {
try magicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile!))
}
catch {
print(error)
}
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event?.subtype == motion {
printAnswer()
randomAnswer()
animation()
showingAnswerAnimation()
magicSound.play()
}
}
The console throws the error at the line,
try magicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile!))
If anyone could help me fix my code that would be great.
I believe the line:
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: ".wav")
should be:
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav")
The dot character is implicit in to the type parameter.
This is how I would write it:
if let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav") {
let magicSound = try? AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile))
}
else {
print( "MagicSound.wav does not exist in main bundle" )
}
Make sure that the file name is an exact case-sensitive match.Also make sure the resource file is at the top level of the bundle (i.e. in the same folder as the .xcodeproj and .xcworkspace file).
Okay this unexpected found nil while unwrapping an Optional value is pretty common errors in SO. You should search more before posting the question.
This magicFile! is the main culprit here. The use of ! means you are unwrapping such a value that you are cent percent sure that the value does contain something other than nil. But if the value is nil your code is supposed to crash and give you a hint that you're assuming something wrong about the value. So change it.
Now comes the rescue. You have multiple options to safely unwrap an Optional value. Such as optional-binding. Having said that you should change your implementation like:
if let magicFile = Bundle.main.url(forResource:"MagicSound" withExtension:"wav") { //As you are supposed to use url, no need to have the path as String
do {
try magicSound = AVAudioPlayer(contentsOf: magicFile)
}
catch {
print(error)
}
}
Try using below Code hope it helps
func playSound() {
guard let url = Bundle.main.url(forResource: "MagicSound", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = magicSound else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
and make sure to import AVFoundation use this

Setup AVAudioPlayer with swift 1.2?

When I tried to setup AVaudioPlayer last time, I used this code:
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
var buttonBeep = AVAudioPlayer()
buttonBeep = self.setupAudioPlayerWithFile("buttonPush", type:"m4a")
And it worked perfectly. Now with Swift 1.2 it seems that I can't do that.
I also tried this code:
var button : AVAudioPlayer?
in didMoveToView:
if let button = self.setupAudioPlayerWithFile("button", type:"m4a") {
self.button = button
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer
}
It gives me an error on let url line - EXC_BAD_INSTRUCTION. I put my audio file in Supporting Files inside my project. What am I doing wrong?
UPDATE: that was my mistake. If you have the same problem — make sure you are adding sounds to a target of your app, not just in project
Try this code:
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
Use it this way:
playBackgroundMusic("button.m4a")
Hope it helps.
It was working fine with 1.2 and I didn't test it right now because I have updated my Xcode and I suggest you to use latest version of Xcode which have swift version 2.0.

fatal error: unexpectedly found nil while unwrapping an Optional value when using AudioPlayer in Swift 2

Hi I am trying to play a music file with a following code in swift 2. Basically I just dragged the audio file with a name f.mp3 to the asses folder and it my code breaks with the following message:
unexpectedly found nil while unwrapping an Optional value. Where exactly I need to put my mp3 file so the IOS can find it. Thank you
var audioPlayer: AVAudioPlayer! = nil
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play()
}
Your code is working fine with my project and here is my complete code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
playMyFile()
}
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Make sure your audio is added into Copy Bundle Resources like this:
If not added then add it this way:
Check THIS sample for more Info.

Issue with downloading youtube videos with swift

I am trying to download youtube video in my app and for that I used THIS and library included in that answer but my app is crashing with error :
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is my swift code:
import UIKit
class ViewController: UIViewController {
let videoID = "hS5CfP8n_js"
var extractor = LBYouTubeExtractor()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func start(sender: AnyObject) {
var url: String = "https://www.youtube.com/watch?v=hS5CfP8n_js"
let testURL = NSURL(string:url)
if testURL != nil {
extractor = LBYouTubeExtractor(URL: testURL, quality: LBYouTubeVideoQualityLarge)
extractor.extractVideoURLWithCompletionBlock({(videoURL, error) in
if error == nil {
println(videoURL)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let data = NSData(contentsOfURL: videoURL)!
let pathToDocs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let fileName = "video_\(self.videoID).mp4"
let yourPath = pathToDocs.stringByAppendingPathComponent(fileName)
data.writeToFile(yourPath, atomically: true)
println("File \(fileName) successfully saved")
})
} else {
println("Failed extracting video URL using block due to error:\(error)")
}
})
}
}
}
my project is crashing at this line:
let data = NSData(contentsOfURL: videoURL)!
But I can get videoURL in console:
http%3A%2F%2Fr3---sn-tv0cgv5qc5oq-nu8e.googlevideo.com%2Fvideoplayback%3Fsver%3D3%26id%3D852e427cff27fe3b%26dur%3D55.681
... ty=small
I don't know what I am missing.
Here is my sample project.

fatal error: unexpectedly found nil while unwrapping an Optional value (Swift)

I am always getting the fatal error: unexpectedly found nil while unwrapping an Optional value. but if i look the the fileURL variable it has some values. please let me know what i missed here:
Error:
Optional(http:/files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3 -- file:///)
fatal error: unexpectedly found nil while unwrapping an Optional value
Code:
if let audioFile = object["audioFile"] as? PFFile {
var audioPath: String = audioFile.url!
var fileURL = NSURL(fileURLWithPath: audioPath as String)
println(fileURL)
audioPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
audioPlayer.volume = volumeSlider.value
audioPlayer.play()
}
This code is working fine with your URL:
let url = "http://files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3"
let soundData = NSData(contentsOfURL: NSURL(string: url)!)
var error: NSError?
self.audioPlayer = AVAudioPlayer(data: soundData, error: &error)
if audioPlayer == nil
{
if let e = error
{
println(e.localizedDescription)
}
}
audioPlayer!.volume = 1.0
audioPlayer!.prepareToPlay()
audioPlayer!.play()
This way you can convert your audio to data which will take some time to play your audio.
Here is another way to play song live:
let url = audioFile.url!
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
player.play()