Skip to content

Instantly share code, notes, and snippets.

@jinal90
Created May 24, 2020 21:17
Show Gist options
  • Save jinal90/72fb99f8556a4432215f387dbbc435c2 to your computer and use it in GitHub Desktop.
Save jinal90/72fb99f8556a4432215f387dbbc435c2 to your computer and use it in GitHub Desktop.
Code snippet to demonstrate simple network call using URLSession in swift.
var dataTask: URLSessionDataTask?
if var urlComponents = URLComponents(string: "https://www.example.com") {
urlComponents.query = "paramKey=value"
guard let url = urlComponents.url else {
return
}
var defaultSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
dataTask = defaultSession.dataTask(with: url) { [weak self] data, response, error in
if let error = error {
print("An error occured: " + error.localizedDescription + "\n")
} else if
let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
var response: JSONDictionary
do {
response = try JSONSerialization.jsonObject(with: data, options: []) as? JSONDictionary
print("Network call successful: \(response)")
} catch let parseError as NSError {
print("Error parsing response")
return
}
}
}
dataTask?.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment