I'm learning to do a basic networking call, and following a tutorial. The tutorial goes through concurrency, and downloading the JSON data in the background thread. I was wondering why in the sharedSession.downloadTaskWithURL
method the queryURL
would be passed as the NSURL object as opposed to the baseURL
. I feel like I'm missing something pretty obvious!
func searchRecipeData() {
let baseURL = NSURL(string: "http://api.recipes.com/v1/api/recipes?_app_id=\(apiID)&_app_key=\(apiKey)")
let queryURL = NSURL(string: "&q=onion+soup", relativeToURL: baseURL)!
let sharedSession = NSURLSession.sharedSession()
let downloadData: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(queryURL, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let data = NSData(contentsOfURL: baseURL!)
println(data)
}
})
// Resumes it even though it hasn't started yet
downloadData.resume()
}
Take a look at the second parameter where you create queryURL. You are passing the baseURL constant. What happens is that the '&q=onion+soup' query parameter is told to be relative to the baseURL. The queryURL constant is the full URL, and it is then passed to downloadTaskWithURL.