为什么函数没有检索数据?

时间:2015-11-07 02:38:40

标签: ios swift itunes-api

我正在尝试从itunes搜索API获取预览链接。我有一个函数,可以在单击按钮时获取信息,但函数未被调用。我想获取结果数组中第一个对象的预览链接如何解决这个问题? enter image description here

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



}

1 个答案:

答案 0 :(得分: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!)
    }
}

由于iOS 9中不推荐使用NSURLConnection,因此我还提供了一种使用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()