Created
October 30, 2018 03:27
-
-
Save zmcartor/c1b2aab34271a21abfd973ddf5c22288 to your computer and use it in GitHub Desktop.
Swift Network Stack
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
enum Result<T> { | |
case success(T) | |
case error(Error) | |
} | |
struct ToDo : Codable { | |
var id: Int | |
var userId: Int | |
var title:String | |
var completed:Bool | |
} | |
typealias callback<T> = (Result<T>) -> Void | |
class Network { | |
let host = URL(string:"https://jsonplaceholder.typicode.com/todos")! | |
func getStuff(id:Int, callback: @escaping callback<ToDo>) -> URLSessionTask { | |
let urlRequest = URLRequest(url: host.appendingPathComponent("\(id)")) | |
let session = URLSession(configuration: URLSessionConfiguration.default) | |
let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in | |
print(response!) | |
if let e = error { | |
callback(.error(e)) | |
return | |
} | |
// TODO should also ret an error to callback, oops!! | |
guard let data = data else { return } | |
do { | |
let todo = try JSONDecoder().decode(ToDo.self, from: data) | |
callback(.success(todo)) | |
return | |
} catch { | |
let err = NSError(domain: "CustomThing", code: 1, userInfo: .none) | |
callback(.error(err)) | |
} | |
} | |
task.resume() | |
return task | |
} | |
} | |
let cb:callback<ToDo> = { result in | |
switch result { | |
case .success(let todo): | |
print("Got the TODO! \(todo)") | |
case .error(let err): | |
print("got an error: \(err)") | |
} | |
} | |
let n = Network() | |
n.getStuff(id: 1, callback: cb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment