Created
May 24, 2020 21:17
-
-
Save jinal90/72fb99f8556a4432215f387dbbc435c2 to your computer and use it in GitHub Desktop.
Code snippet to demonstrate simple network call using URLSession in swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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