Last active
October 13, 2018 09:54
-
-
Save Salman544/6dcfe2a11cbbc7ae752afbac9ca3d3f9 to your computer and use it in GitHub Desktop.
This file contains 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
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