Skip to content

Instantly share code, notes, and snippets.

@RockinPaul
Last active January 24, 2019 13:32
Show Gist options
  • Save RockinPaul/7cb41e927cd700c5af196ccf5d5a06fc to your computer and use it in GitHub Desktop.
Save RockinPaul/7cb41e927cd700c5af196ccf5d5a06fc to your computer and use it in GitHub Desktop.
ApiService: Swift+URLSession
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