Sam L. Sam L. - 2 months ago 11x
Swift Question

Unexpectedly unwrapping an optional to find a nil after an API call to Spotify

So I know this may be a bit specific but I've been staring at my code and am unable to resolve this issue. Basically, I'm making a network call to spotify to obtain a certain playlist and pass a number that will ultimately determine the number of songs I get back. The code is basically as follows:

// A network call is made just above to return somePlaylist
let playlist = somePlaylist as! SPTPartialPlaylist
var songs: [SPTPartialTrack] = []

// load in playlist to receive back songs
SPTPlaylistSnapshot.playlistWithURI(playlist.uri, session: someSession) { (error: NSError!, data: AnyObject!) in

// cast the data into a correct format
let playlistViewer = data as! SPTPlaylistSnapshot
let playlist = playlistViewer.firstTrackPage

// get the songs
for _ in 1...numberOfSongs {
let random = Int(arc4random_uniform(UInt32(playlist.items.count)))
songs.append(playlist.items[random] as! SPTPartialTrack)

The problem comes at the portion of code that initializes random. In maybe 1 in 20 calls to this function I, for whatever, reason unwrap a nil value for playlist.items.count and can't seem to figure out why. Maybe it's something I don't understand about API calls or something else I'm failing to see but I can't seem to make sense of it.

Anyone have any recommendations on addressing this issue or how to go about debugging this?


Ok, after sleeping on it and working on it some more I seem to have resolved the issue. Here's the error handling I implemented into my code.

if let actualPlaylist = playlist, actualItems = actualPlaylist.items {
        if actualItems.count == 0 {
            SongScraper.playlistHasSongs = false
            print("Empty playlist, loading another playlist")

        for _ in 1...numberOfSongs {
            let random = Int(arc4random_uniform(UInt32(actualItems.count)))
            songs.append(actualPlaylist.items[random] as! SPTPartialTrack)

        completionHandler(songs: songs)
    else {
        print("Returned a nil playlist, loading another playlist")
        SongScraper.playlistHasSongs = false