Skip to content

Instantly share code, notes, and snippets.

@Salman544
Last active October 13, 2018 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Salman544/6dcfe2a11cbbc7ae752afbac9ca3d3f9 to your computer and use it in GitHub Desktop.
Save Salman544/6dcfe2a11cbbc7ae752afbac9ca3d3f9 to your computer and use it in GitHub Desktop.
struct NetworkRequest<T: Decodable> {
public enum FetchResults {
case success(response: T)
case error(error: String)
}
static func fetchJson(with url: URL, completion: @escaping (FetchResults) -> Void) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.error(error: error.localizedDescription))
return
}
guard let data = data else {
completion(.error(error: "Data is invalid"))
return
}
do {
completion(.success(response: try JSONDecoder().decode(T.self, from: data)))
} catch let error {
completion(.error(error: error.localizedDescription))
}
}.resume()
}
}
struct User: Decodable {
let name: String
let uid: String
}
if let url = URL(string: "some url") {
NetworkRequest<User>.fetchJson(with: url) { (result) in
switch result {
case .success(let user):
print(user)
case .error(let msg):
print(msg)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment