Simple GET request
suggest changeThis sample is Swift 2. The completion is not on the main thread. error is nil for an HTTP error status, so also check the response. url! crashes when the string is not a URL.
// define url
let url = NSURL(string: "https://urlToGet.com")
//create a task to get data from a url
let task = NSURLSession.sharedSession().dataTaskWithURL(url!)
{
/*inside this block, we have access to NSData *data, NSURLResponse *response, and NSError *error returned by the dataTaskWithURL() function*/
(data, response, error) in
if error == nil
{
// Data from the request can be manipulated here
}
else
{
// An error occurred
}
}
//make the request
task.resume()
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents