所以我知道这可能有点具体,但我一直在盯着我的代码,我无法解决这个问题。基本上,我正在进行网络调用以获取某个播放列表并传递一个最终确定我收到的歌曲数量的数字。代码基本如下:
// 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)
}
}
问题出现在初始化随机的代码部分。在20个调用此函数的过程中,我可能会因为打开playlist.items.count的nil值而无法解决原因。也许这是我不了解API调用或其他我无法看到的东西,但我似乎无法理解它。
任何人都有任何关于解决此问题的建议或如何进行调试?
答案 0 :(得分:0)
好的,在睡上并继续工作之后,我似乎已经解决了这个问题。这是我在代码中实现的错误处理。
if let actualPlaylist = playlist, actualItems = actualPlaylist.items {
if actualItems.count == 0 {
SongScraper.playlistHasSongs = false
print("Empty playlist, loading another playlist")
return
}
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
return
}