iosswiftitunes-api

Why is the function(s) not retrieving the data?


I am trying the get the preview link from the itunes search api. I have a function that will get the information when the button is clicked, but the function is not being called. I want to get the preview link of the first object in the results array How do I fix this? 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()



}

Solution

  • The way to grab the previewUrl is to grab the value for a single result array member such as the first one having index 0 and then pulling the value for the previewUrl key. For example:

    if jResult.count>0 && jResult["results"]!.count>0 {
        var results: NSArray = jResult["results"]as! NSArray
    
        if let previewUrl = results[0]["previewUrl"] {
            print(previewUrl!)
        }
    }
    

    Since NSURLConnection is deprecated in iOS 9, I'll also give you a way of using NSURLSession to retrieve the previewUrls from the iTunes API.

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