Last active
January 24, 2019 13:32
-
-
Save RockinPaul/7cb41e927cd700c5af196ccf5d5a06fc to your computer and use it in GitHub Desktop.
ApiService: Swift+URLSession
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
class ApiService { | |
static let sharedInstance = ApiService() | |
let BASE_URL = "https://restcountries.eu" | |
// MARK: - List of countries | |
func countries(_ completion: @escaping(_ result: [Country]?, _ error: Error?) -> Void) { | |
let urlString = BASE_URL + "/rest/v2/all" | |
guard let url = URL(string: urlString) else { return } | |
URLSession.shared.dataTask(with: url) { (data, response, error) in | |
if error != nil { | |
completion(nil, error) | |
} | |
guard let data = data else { return } | |
//Implement JSON decoding and parsing | |
do { | |
// let jsonResponse = try JSONSerialization.jsonObject(with: | |
// data, options: []) | |
// print(jsonResponse) // Uncomment for debug purposes | |
let countriesData = try JSONDecoder().decode([Country].self, from: data) | |
// In case of single root key with a value as array, | |
// we can use something like this: [String : [Vehicle]].self | |
DispatchQueue.main.async { | |
completion(countriesData, nil) | |
} | |
} catch let jsonError { | |
print(jsonError) | |
} | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment