Skip to content

Instantly share code, notes, and snippets.

@minhwang
Created November 8, 2016 10:20
Show Gist options
  • Save minhwang/18743fc55ea57447c75a734f8c42c2a1 to your computer and use it in GitHub Desktop.
Save minhwang/18743fc55ea57447c75a734f8c42c2a1 to your computer and use it in GitHub Desktop.
How to write code to request GET data
func requestGET(stringURL url:String) -> URLSessionDataTask? {
var task: URLSessionDataTask? = nil
guard let url: URL = URL(string: url) else {
print("URL is invalid..!!")
return task
}
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
/*
* You should pass a nil completion handler only when creating tasks in sessions whose delegates include a urlSession(_:dataTask:didReceive:) method.
*/
task = urlSession.dataTask(with: URLRequest(url: url), completionHandler: {(data: Data?, response: URLResponse?, error: Error?) in
/*
* If a response from the server is received, regardless of whether the request completes successfully or fails,
* the response parameter contains that information.
*/
guard let httpResponse = response as? HTTPURLResponse else {
print("The response is nil. Something is wrong..!!")
return
}
print("Status Code: \(httpResponse.statusCode)\n")
if let error = error {
print("Error: " + error.localizedDescription)
return
}
guard let _ = data else {
print("The data is nil. Something is wrong..!!")
return
}
})
task!.resume()
return task
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment