Streaming audio from parse in Swift 3

296 views Asked by At

I'm using Back4app as Parse server I'm trying to stream audio from Prase everything works fine , but if I click on any index (except index 0) on tableview I got error "fatal error: unexpectedly found nil while unwrapping an Optional value"

I don't know why when I click on Index 0 it work fine but any other index I got error !

func grabSong() {        
    let SongQuery = PFQuery(className: "Songs")

    SongQuery.getObjectInBackground(withId:iDArray[SelectedSongNumber!] ,block: { (object : PFObject?, error : Error?) ->  Void in           
        if let AudioFileURLTemp : PFFile = object?.value(forKey: "SongFile") as? PFFile {            
            print(AudioFileURLTemp)

            audioP = AVPlayer(url: NSURL(string: AudioFileURLTemp.url!) as! URL)            
            audioP.play()        
        }       
    })
}

I got the error on this line:

audioP = AVPlayer(url: NSURL(string: AudioFileURLTemp.url!) as! URL)
1

There are 1 answers

1
Basel On BEST ANSWER

I found out why I got the error. It's because some of the song names have spaces in them, but the first song doesn't have any spaces in its names. So I tried to copy the link in the browser and see how the browser deals with spaces. I found out it replaces spaces with %20.

So I replaced every space with "%20" and now it works.

Correct code

func grabSong() {        
    let SongQuery = PFQuery(className: "Songs")
    SongQuery.getObjectInBackground(withId:iDArray[SelectedSongNumber] ,block: { (object : PFObject?, error : Error?) ->  Void in                    
        if let AudioFileURLTemp : PFFile = object?.value(forKey: "SongFile") as? PFFile {                       
            var songID = AudioFileURLTemp.url!.replacingOccurrences(of: " ", with: "%20")

            audioP = AVPlayer(url: URL(string:songID)!)
            audioP.play()
        }
    })
}