I am downloading the audio message first then play it using Avaudioplayer
downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(urlStr, completionHandler: { (URL, response, error) -> Void in
self.play(URL!)
})
downloadTask
This works fine, but if I call play(URL) method after saving the response URL that I have stored in NSUserDefaults. The URL is same in both cases. I have checked it. its something like:
file:///Users/mymac/Library/Developer/CoreSimulator/Devices/X-CD91-XXXXXXX-XXX-XXXXXX/data/Containers/Data/Application/XXXXXXX-XXXX-XXXXXXXXXX/tmp/CFNetworkDownload_InUTA3.tmp
Passing this file url to:
func play(url : NSURL) {
do {
player = try AVAudioPlayer(contentsOfURL: url)
player.prepareToPlay()
player.play()
} catch let error as NSError {
//self.player = nil
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
Url path is same, but the audioPlayer is unable to play the sound, it shows the following error:
The operation couldn’t be completed. (OSStatus error 2003334207.)
Can anyone guide me in this regard?
Thanks.
play
with a URL that you have stored in your UserDefaults...it works? And if you call it straight here in the completion handler ofdownloadTaskWithURL
it does not work...correct? Or is it the other way around? – pbodskcompletionHandler
you must move the file somewhere else. As it says here about thelocation
: developer.apple.com/reference/foundation/nsurlsession/… "The location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.", so if you don't do that already, then that could be why it works in thecompletionHandler
and not later. – pbodskURL
and since there is no longer an item at that location which you've saved in your UserDefaults, it crashes – pbodsk