Search code examples
swiftxcodeurlfirebase-storageavaudioplayer

Getting URL from firebase storage and setting it to an AVAudioPlayer always throws error (swift xcode)


I'm trying to download a URL from Firebase storage and save it to an AVAudioPlayer

func loadAudio(post: CompPost, completion: @escaping (AVAudioPlayer) -> ())
    {
        let audioRef = Storage.storage().reference().child("cPosts").child(post.uid).child("Audio").child(post.mp3)
        audioRef.downloadURL
        { (url, error) in
            print("mp3filename: " + post.mp3)
            guard error == nil else
            {
                print(error!.localizedDescription)
                return /**alert**/ }
            let audioURL = url
            print("url:" + audioURL!.absoluteString)
            do
            {
                try self.audioPlayer = AVAudioPlayer(contentsOf: audioURL!)
                completion(self.audioPlayer)
                print("THIS HAS LOADED")
            }
            catch
            {
                print("COULD NOT ASSIGN URL") /**alert**/
                //ERROR here that keeps on happening :(
            }
        }
    }

I know for a fact it's the correct file from storage, and that there's no error getting the url because of my print statements to check, however, for some reason there is an issue setting this URL to the contents of my AVAudioPlayer, audioPlayer


Solution

  • What @jnpdx meant (I think is) - this way you can let iOS stream directly from the remote URL, without handling downloading the file yourself

    func loadAudio(post: CompPost, completion: @escaping (AVAudioPlayer) -> ())
    {
        let audioRef = Storage.storage().reference().child("cPosts").child(post.uid).child("Audio").child(post.mp3)
        audioRef.downloadURL
        { (url, error) in
            print("mp3filename: " + post.mp3)
            guard error == nil else
            {
                print(error!.localizedDescription)
                return /**alert**/ }
            let audioURL = url
            print("url:" + audioURL!.absoluteString)
            do
            {
                **try self.audioPlayer = AVPlayer(url: audioURL!)**
                completion(self.audioPlayer)
                print("THIS HAS LOADED")
            }
            catch
            {
                print("COULD NOT ASSIGN URL - Error = /(error)") /**alert**/
                //ERROR here that keeps on happening :(
            }
        }
    }