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()
Related
If my link does not return data how do I check in swiftyJSON,
I got this error : fatal error: unexpectedly found nil while unwrapping an Optional value
var URLString = mylink
URLString = URLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let url = NSURL(string: URLString)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, innerError) in
let jsonData = NSData(contentsOfURL: url)! as NSData? //>> here is the error fatal error: unexpectedly found nil while unwrapping an Optional value
let readableJson = JSON(data: jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil)
let jjson = readableJson[0]
let ID = jjson["Title"]
})
}
task.resume()
You should avoid the force unwrap "!".
Try this
func foo(urlAsString:String) {
guard let
urlAsStringEscaped = urlAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding),
url = NSURL(string: urlAsStringEscaped)
else { fatalError() }
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
if let data = data where error == nil {
let json = JSON(data: data)
let id = json[0]["Title"].string
}
}
task.resume()
}
I try to make link to waze in Swift after i insert the url i get a fatal error.
My code:
let newName:String = closest.name.stringByReplacingOccurrencesOfString(" ", withString: "&", options: NSStringCompareOptions.LiteralSearch, range: nil)
print(closest.name)
print(newName)
let url:String = "waze://?q=\(newName)"
print(url)
let navAdd: NSURL? = NSURL(string:url)// here is the error
let wazeApp: NSURL? = NSURL(string: "http://itunes.apple.com/us/app/id323229106")!
print(navAdd)
if(true){
UIApplication.sharedApplication().openURL(navAdd!)
}else{
UIApplication.sharedApplication().openURL(wazeApp!)
}
and the error is:
fatal error: unexpectedly found nil while unwrapping an Optional value
You have unwrapped an optional with out checking if its not nil.
if let navAdd = NSURL(string:url) {
UIApplication.sharedApplication().openURL(navAdd)
} else if let wazeApp = NSURL(string:"http://itunes.apple.com/us/app/id323229106"){
UIApplication.sharedApplication().openURL(wazeApp)
} else {print("Url not found")}
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.
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.
}
I'm working on a json retrieving project or whatever, and I'm getting a fatal error while unwrapping a json. I think that the issue is that url is nil and I'm trying to unwrap it, but I'm not sure.
func getXRPData(urlString: String){
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data)
})
}
task.resume()
}
func setLabels(xrpDataL: NSData){
var jsonError: NSError?
var percent = "%"
var dollarSIGN = "$"
let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as! NSDictionary
//supply of xrp
if let supply = json["supply"] as? String{
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let result = numberFormatter.numberFromString(supply){
var finalResult = numberFormatter.stringFromNumber(result)
totalXRP.text = finalResult
}
}
Instead of force unwrapping, you should unwrap the results of JSONObjectWithData with an optional binding (if let) and a conditional downcast (as?):
if let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as? NSDictionary {
// Continue parsing
} else {
// Handle error
}