Skip to content

Instantly share code, notes, and snippets.

@fundon
Created July 24, 2016 06:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fundon/46c130f68769cab7aaf4ca54f97b2e7b to your computer and use it in GitHub Desktop.
objcio/S01E01-networking
//: To run this playground start a SimpleHTTPServer on the commandline like this:
//:
//: `python -m SimpleHTTPServer 8000`
//:
//: It will serve up the current directory, so make sure to be in the directory containing episodes.json
import UIKit
import PlaygroundSupport
typealias JSONDictionary = [String: AnyObject]
let url = NSURL(string: "http://localhost:8000/episodes.json")!
struct Episode {
let id: String
let title: String
}
extension Episode {
init?(dictionary: JSONDictionary) {
guard let id = dictionary["id"] as? String,
let title = dictionary["title"] as? String else { return nil }
self.id = id
self.title = title
}
}
struct Media {}
struct Resource<A> {
let url: NSURL
let parse: (NSData) -> A?
}
extension Resource {
init(url: NSURL, parseJSON: (AnyObject) -> A?) {
self.url = url
self.parse = { data in
let json = try? JSONSerialization.jsonObject(with: data as Data, options: [])
return json.flatMap(parseJSON)
}
}
}
extension Episode {
static let all = Resource<[Episode]>(url: url, parseJSON: { json in
guard let dictionaries = json as? [JSONDictionary] else { return nil }
return dictionaries.flatMap(Episode.init)
})
}
final class Webservice {
func load<A>(resource: Resource<A>, completion: (A?) -> ()) {
URLSession.shared.dataTask(with: resource.url as URL) { data, _, _ in
guard let data = data else {
completion(nil)
return
}
completion(resource.parse(data))
}.resume()
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
Webservice().load(resource: Episode.all) { result in
print(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment