我正在从itunes api获取预览歌曲并且播放,但是当我再次单击该按钮暂停它时,歌曲必须完成它才会暂停(它打印"暂停"在控制台中)。我该如何解决?
func playit(sender: UIButton!) {
let playButtonrow = sender.tag
print(ret[playButtonrow])
switch(buttonState){
case 0:
let searchTerm: String = ret[playButtonrow]
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)!
let request: NSURLRequest = NSURLRequest(URL: url)
let ctn: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
print("Search iTunes API at URL \(url)")
ctn.start()
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)
player.rate = 1.0
player.play()
}
} catch let jsonError as NSError {
}
}
task.resume()
}
buttonState = 1;
break
case 1:
player.pause()
print("player paused")
buttonState = 0
default: break
}
}