1

我正在尝试从 iTunes 搜索 api 获取预览链接。我有一个函数可以在单击按钮时获取信息,但没有调用该函数。我想获取结果数组中第一个对象的预览链接如何解决这个问题?在此处输入图像描述

var d: NSMutableData = NSMutable Data()

var tData: NSArray = NSArray() 

func ctn(receivedResponse: NSURLConnection!, receivedResponse response:  NSURLResponse!) {
// clear out the data object if a new request was received.
self.d = NSMutableData()
}

func ctn(ctn: NSURLConnection!, receivedData d: NSData!) {
  self.d.appendData(d)
}
func ctnFinishedLoading(ctn: NSURLConnection!) throws {
var err: NSError
var jResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jResult.count>0 && jResult["results"]!.count>0 {
    var results: NSArray = jResult["results"]as! NSArray
    self.tData = results
    print(tData)
    //self.appsTableView.reloadData()
}

   }


func playit(sender: UIButton!) {



let cell = table.dequeueReusableCellWithIdentifier("cell")

let playButtonrow = sender.tag

print(ret[playButtonrow])

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()



}
4

1 回答 1

1

获取 previewUrl 的方法是获取单个结果数组成员的值,例如索引为 0 的第一个成员,然后拉取 previewUrl 键的值。例如:

if jResult.count>0 && jResult["results"]!.count>0 {
    var results: NSArray = jResult["results"]as! NSArray

    if let previewUrl = results[0]["previewUrl"] {
        print(previewUrl!)
    }
}

由于NSURLConnection在 iOS 9 中已弃用,我还将为您提供一种NSURLSession用于从 iTunes API 检索 previewUrls 的方法。

let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
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
        {
            // The search is complete.
            for result in dict["results"] as! NSArray {
                if let previewUrl = result["previewUrl"] {
                    print(previewUrl!)
                }
            }
        }
    } catch let jsonError as NSError {
        // Handle error.
    }
}
task.resume()
于 2015-11-07T05:27:11.257 回答