我很安全地展開,但由於某種原因,當它找不到與給定標題相同的歌曲時,應用程序仍然崩潰。這是爲什麼發生?我怎樣才能解決這個問題?爲什麼iTunes應用程序無法在itunes API中找到歌曲時會崩潰?
let searchTerm: String = playertitle.text!
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
print("Search iTunes API at URL \(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
do {
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
let previewUrl = NSURL(string: (dict["results"]![0]["previewUrl"] as? String)!)!
print(previewUrl)
player = AVPlayer(URL: previewUrl)
}
} catch let jsonError as NSError {
}
}
task.resume()
}
}
我發現錯誤發生的地方。它發生在'let previewUrl'行。由於該數組是空的,因此沒有任何數據可以獲取。 – tman0542
是的,我發現太 – HackerManiac